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 如下:
4.0.0 org.springframework.boot spring-boot-starter-parent2.5.5 com.cmc springbt-06-data-mybatis20.0.1-SNAPSHOT springbt-06-data-mybatis2 Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter2.2.0 mysql mysql-connector-javaruntime com.alibaba druid1.2.8 log4j log4j1.2.17 org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
【1.2】druid数据源配置
步骤1,引入 druid 依赖;
com.alibaba
druid
1.2.8
log4j
log4j
1.2.17
步骤3, 数据源druid配置; application.yml
# 配置springboot数据源
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.163.204:3306/mybatis
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 启用druid数据源
# 数据源其他配置
initialSize: 6
minIdle: 6
maxActive: 26
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
druid 监控servlet配置;
// 导入druid数据源
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
// 配置druid监控
// 1 配置一个管理后台的servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 配置相关参数
Map 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
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
// 配置相关参数
Map 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;
}
@Override
public 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 {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public 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 {
@Autowired
DepartmentMapper 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 全局配置文件
【2.2】sql接口与sql映射文件
EmployeeMapper.java
// @Mapper 或 @MapperScan 把接口扫描装配到容器中
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee empt);
}
【2.3】在 application.yml 中指定 mybatis配置INSERT INTO employee (last_name, email, gender, d_id) VALUES(#{lastName}, #{email}, #{gender}, #{dID})
# 配置mybatis 全局配置文件和mapper路径 mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml
【2.4】编写 EmpController处理 employee请求
@RestController
public class EmpController {
@Autowired
EmployeeMapper 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



