【README】
1.本文记录了 springboot2.5.5 配置 mybatis的步骤;
2.配置mybatis 分为注解和配置两种方式;
3.引入mybatis,包括了
- 创建springbt项目;
- druid数据源配置;
- 数据库表与javabean;
- mybatis配置与sql映射;
- 用户请求controller处理;
【1】springboot使用@注解引入mybatis
【1.1】创建springboot项目
步骤1, 新建springboot项目;
步骤2,选择依赖,包括springweb,mysql驱动,mybatis;(当然也可以手动录入 maven 依赖)
因为 mybatis-spring-boot-starter 引入了 jdbc starter,所需这里无需引入;
pom.xml 如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.5</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.cmc</groupId><artifactId>springbt-06-data-mybatis2</artifactId><version>0.0.1-SNAPSHOT</version><name>springbt-06-data-mybatis2</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><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.2.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- 引入druid数据源 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency><!-- 需要引入log4j,因为druid使用了log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
【1.2】druid数据源配置
步骤1,引入 druid 依赖;
<!-- 引入druid数据源 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency><!-- 需要引入log4j,因为druid使用了log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>
步骤3, 数据源druid配置; application.yml
# 配置springboot数据源
spring:datasource:username: rootpassword: rooturl: jdbc:mysql://192.168.163.204:3306/mybatisdriver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource # 启用druid数据源# 数据源其他配置initialSize: 6minIdle: 6maxActive: 26maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
druid 监控servlet配置;
// 导入druid数据源
@Configuration
public class DruidConfig {@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druid() {return new DruidDataSource();}// 配置druid监控// 1 配置一个管理后台的servlet@Beanpublic ServletRegistrationBean statViewServlet() {ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");// 配置相关参数Map<String, String> params = new HashMap<>();params.put("loginUsername", "admin");params.put("loginPassword", "admin");params.put("allow", "localhost"); // 默认允许所有访问params.put("deny", "192.168.163.204"); // 默认允许所有访问bean.setInitParameters(params);return bean;}// 2 配置一个监控的filter@Beanpublic FilterRegistrationBean webStatFilter() {FilterRegistrationBean bean = new FilterRegistrationBean<>();bean.setFilter(new WebStatFilter());// 配置相关参数Map<String, String> params = new HashMap<>();params.put("exclusions", "*.js,*.css,/druid/*");bean.setInitParameters(params);bean.setUrlPatterns(Arrays.asList("/*"));return bean;}
}
【1.3】数据库表与javabean
步骤1,数据库表
CREATE TABLE `employee` (`id` int NOT NULL AUTO_INCREMENT,`last_name` varchar(255) DEFAULT NULL,`email` varchar(255) DEFAULT NULL,`gender` int DEFAULT NULL,`d_id` int DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb3
;CREATE TABLE `department` (`id` int NOT NULL AUTO_INCREMENT,`department_name` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb3
;
步骤2,编写db表映射的javabean;
public class Department {private Integer id;private String departmentName;public Department(){}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;MybatisAutoConfiguration conf = null;}public String getDepartmentName() {return departmentName;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}@Overridepublic String toString() {return "Department{" +"id=" + id +", departmentName='" + departmentName + '\'' +'}';}
}public class Employee {private Integer id;private String lastName;private Integer gender;private String email ;private Integer dId;public Employee(){}.............
}
【1.4】mybatis全局配置与sql映射
步骤1,mybatic全局配置类(也可以通过 mybatis-config.xml 来实现);
@MapperScan 注解用于扫描 传入包下的所有Mapper类;
@org.springframework.context.annotation.Configuration
@MapperScan("com.cmc.springbt.mapper")
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer() {return new ConfigurationCustomizer() {@Overridepublic void customize(Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true); // 开启驼峰}};}
}
步骤2,编写 mybatis maper,sql操作接口;
MybatisConfig 中的注解 MapperScan 已经可以扫描到 DepartmentMapper, 这里无需 添加@Mapper 注解; 两者取1 即可;
// 指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id} ")public Department getDeptByID(int id);@Delete("delete from department where id=#{id}")public int deleteDeptById(int id) ;@Insert("insert into department(department_name) values(#{departmentName})")@Options(useGeneratedKeys = true,keyProperty = "id")public int insertDept(Department dept);@Update("update department set department_name=#{departmentName} where id=#{id}")public int updateDept(Department dept);
}
【1.5】用户请求controller处理,使用 DepartmentMapper
步骤1,请求controller处理
@@RestController
public class DeptController {@AutowiredDepartmentMapper departmentMapper;@GetMapping("dept/{id}")public Department getDepartment(@PathVariable("id") Integer id) {return departmentMapper.getDeptByID(id);}@GetMapping("dept")public Department insertDept(Department dept) {departmentMapper.insertDept(dept);return dept;}
}
注意,这是 @RestController, 而不是 @Controller;因为我是写数据到servlet,而不是到某个具体视图;
步骤2,修改springboot web项目配置(或有);
application.properties
# 服务器配置
server.port=8085
server.servlet.context-path=/springbt-mybatis2
小结,整体项目结构
【1.6】访问效果
http://localhost:8085/springbt-mybatis2/dept?departmentName=zhangsan01
http://localhost:8085/springbt-mybatis2/dept/13 http://localhost:8085/springbt-mybatis2/dept/13
【2】springboot使用配置引入mybatis
【2.1】 编写mybatis全局配置与sql文件
mybatis-config.xml 全局配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>
【2.2】sql接口与sql映射文件
EmployeeMapper.java
// @Mapper 或 @MapperScan 把接口扫描装配到容器中
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee empt);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cmc.springbt.mapper.EmployeeMapper"><!-- 通过id查询emp --><select id="getEmpById" resultType="com.cmc.springbt.bean.Employee">SELECT id, last_name, email, gender, d_idFROM employeewhere id = #{id}</select><!-- 插入emp --><insert id="insertEmp">INSERT INTO employee(last_name, email, gender, d_id)VALUES(#{lastName}, #{email}, #{gender}, #{dID})</insert></mapper>
【2.3】在 application.yml 中指定 mybatis配置
# 配置mybatis 全局配置文件和mapper路径
mybatis:config-location: classpath:mybatis/mybatis-config.xmlmapper-locations: classpath:mybatis/mapper/*.xml
【2.4】编写 EmpController处理 employee请求
@RestController
public class EmpController {@AutowiredEmployeeMapper employeeMapper;@GetMapping("/emp/{id}")public Employee getEmp(@PathVariable("id") Integer id) {return employeeMapper.getEmpById(id);}
}
小结, mybatis配置后的整体目录结构;
【2.5】访问效果
http://localhost:8085/springbt-mybatis2/emp/1