目录
一、SpringBoot整合MyBatis
引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
依赖关系
项目构建
1、在resources下创建department.sql
和employee.sql
,项目启动时创建表(在数据库中自动生成)
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
2、实体类
public class Department {
private Integer id;
private String departmentName;
// 省略 getter/setter 方法
}
public class Employee {
private Integer id;
private String lastName;
private Integer gender;
private String email;
private Integer dId;
// 省略 getter/setter 方法
}
3、配置文件
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_mybatis
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# 数据源更改为druid
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 连接池配置
# 配置初始化大小、最小、最大
initial-size: 1
min-idle: 1
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 3000
validation-query: SELECT 1 FROM DUAL
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
filters: stat,wall,slf4j
# 配置web监控,默认配置也和下面相同(除用户名密码,enabled默认false外),其他可以不配
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: root
allow: 127.0.0.1
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
二、Mybatis增删改查(使用注解方式)
- 创建
mapper
接口
/**
* Description:
*
* @author zygui
* @date 2020/4/17 16:10
*/
// 指定这是一个操作数据库的mapper
@Mapper // 这里必须要添加这个Mapper注解; 也可以在主启动类上统一通过@MapperScan(value="con.zy.mapper")来扫描
public interface DepartmentMapper {
@Select("SELECT * FROM department WHERE id = #{id}")
public Department getDeptById(@Param("id") Integer id);
@Delete("DELETE FROM department WHERE id = #{id}")
public int deleteDeptById(@Param("id") Integer id);
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert("INSERT INTO department(department_name) VALUES(#{departmentName})")
public int insertDept(Department department);
@Update("UPDATE department SET department_name = #{departmentName} WHERE id = #{id}")
public int updateDept(Department department);
}
- 创建
Controller
@RestController
public class DeptController {
@Resource
private DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id) {
return departmentMapper.getDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department) {
int count = departmentMapper.insertDept(department);
if (count > 0) {
System.out.println("插入数据成功");
}
return department;
}
-
访问:
http://localhost:8080/dept?departmentName=gzy
添加一条数据访问:
http://localhost:8080/dept/1
获取数据
Mybatis配置
开启驼峰命名法
我们的实体类和表中的列名一致,一点问题也没有
我们把department表的departmentName列名改为department_name看看会发生什么
访问:http://localhost:8080/dept/1获取数据
[{“id”:1,“departmentName”:null}]
由于列表和属性名不一致,所以就没有封装进去,我们表中的列名和实体类属性名都是遵循驼峰命名规则的,可以开启mybatis的开启驼峰命名配置
# 开启驼峰映射
mybatis:
configuration:
map-underscore-to-camel-case: true
然后重启项目,重新插入数据,再查询就发现可以封装进去了
也可以通过向spring容器中注入org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer的方法设置mybatis参数
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
// 开启驼峰命名映射
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
Mapper扫描
使用@mapper
注解的类可以被扫描到容器中,但是每个Mapper都要加上这个注解就是一个繁琐的工作,能不能直接扫描某个包下的所有Mapper接口呢,当然可以,在springboot启动类上加上@MapperScan
@MapperScan(“cn.clboy.springbootmybatis.mapper”)
三、Mybatis增删改查(XML配置方式)
- 创建mybatis全局配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 开启数据库中列名和pojp的驼峰命名映射 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
- 创建EmployeeMapper接口
@Mapper 或者 @MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {
public Employee getEmpById(@Param("id") Integer id);
public void insertEmp(Employee employee);
}
- 创建EmployeeMapper.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.zy.mapper.EmployeeMapper">
<select id="getEmpById" resultType="com.zy.pojo.Employee">
SELECT * FROM employee WHERE id = #{id};
</select>
<insert id="insertEmp">
INSERT INTO employee (lastName, email, gender, d_id) VALUSE (#{lastName}, #{email}, #{gender}, #{dId})
</insert>
</mapper>
- 配置文件(application.yaml)中指定配置文件和映射文件的位置
# 加载mybati的全局配置文件
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
- Controller
@RestController
public class EmpController {
@Resource
private EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
public Employee getEmp(@PathVariable("id") Integer id) {
return employeeMapper.getEmpById(id);
}
}
- 测试