欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot整合Mybatis入门一看就懂

程序员文章站 2022-06-05 19:59:45
...

引入pom依赖:

  • Mybatis依赖、数据库驱动依赖、数据库连接池依赖

<dependencies>
	<dependency>
    	<groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
    	<groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
    	<groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.19</version>
    </dependency>
</dependencies>

创建数据库、编写与数据库字段一一对应的实体类

  • 创建数据库举例
CREATE TABLE t_user(
	id VARCHAR(40) PRIMARY KEY,
	username VARCHAR(40),
	realname VARCHAR(40),
	password VARCHAR(40),
	sex VARCHAR(8)
);


CREATE TABLE t_emp(
	id VARCHAR(40) PRIMARY KEY,
	name VARCHAR(60),
	salary DOUBLE(7,2),
	bir date
);
  • 连接数据库的数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ems_thymeleaf?serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456
  • 配置**Mapper.xml的位置信息
mybatis.mapper-locations=classpath:com/example/demo/mapper/*.xml
  • 用户类和员工类举例
@Data 
@AllArgsConstructor  //全参构造
@NoArgsConstructor  //无参构造
public class User{
    private String id;
    private String username;
    private String realname;
    private String password;
    private String sex;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp{
    private String id;
    private String name;
    private Double salary;
    private Date bir;
}
  • 注解的作用
  1. @Data 加了这个注解主要是为了让实体类的代码更加简洁,这样子就不用生成getter、setter还有toString方法
  2. @AllArgsConstructor 提供了类的全参构造
  3. @NoArgsConstructor 提供类的无参构造
  • 以上3个注解都要引入lombok依赖,引入方法如下
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
    <scope>provided</scope>
</dependency>

编写DAO层接口(或者Mapper)

  • DAO 以保存一个用户为例
public interface UserDAO {
    void save(User user);
}

对应的UserDAOMapper.xml写法

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserDAO">
    <!--注册-->
    <insert id="save" parameterType="com.example.demo.entity.User">
        insert into t_user values(#{id},#{username},#{realname},#{password},#{sex})
    </insert>
</mapper>