一、基础环境搭建
1、引入依赖
<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>1.3.2</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>
</dependency>
</dependencies>
注意这里的mybatis-spring-boot-starter并不是SpringBoot官方出的启动器(starter),而是mybatis出的(SpringBoot官方的starter都是以spring-boot-starter-模块名的格式命名的),引入mybatis-spring-boot-starter时会为我们引入其他的一些依赖,如mybatis等,如下图所示:
2、使用druid作为数据源:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
数据源的配置:
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.2.107:3306/docker_jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
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的监控
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties("spring.dataSource")
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
3、项目启动建表,将建表sql放在类路径下的sql文件夹下,并做如下配置:
spring:
datasource:
schema:
- classpath:sql/department.sql
- classpath:sql/employee.sql
注意
:表创建完之后,记得把schema的配置注释掉,不然会再次创建表,导致程序错误或者数据丢失
4、封装和表结构对应的JavaBean
public class Department {
private Integer id;
private String departmentName;
...
}
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Integer dId;
...
}
二、注解版mybatis
1、创建一个mapper接口:mybatis会为我们完成具体的实现(mybatis会实现注解有@Mapper的接口)
@Mapper//告诉mybatis这是一个操作数据库的mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id = #{id}")
public int deleteDeptById(Integer id);
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName = #{departmentName} where id = #{id}")
public int updateDept(Department department);
}
也可以在主配置类中使用@MapperScan来指定mybatis扫描的包,这样就不用再在每个Mapper的Interface接口上标注@Mapper注解了:相当于该包下的每个接口都使用@Mapper注解
@MapperScan("com.bdm.springboot.mapper")
@SpringBootApplication
public class SpringbootDataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDataMybatisApplication.class, args);
}
}
2、编写一个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 department){
departmentMapper.insertDept(department);
return department;
}
}
在测试的时候会发现insertDept接口返回的department对象是没有id的,我们可以通过配置接口方法insertDept,来使插入后的department拥有id(是mybatis通过反射的方式给对象属性赋值):使用@Options注解
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
另外跟mybatis配置相关的定义都在MybatisAutoConfiguration类中,包括SqlFactory的配置也在该类中
3、问题:这时数据库表中的字段名必须和JavaBean中的属性名完全一致,否则是映射不上的,这时我们可以编写一个配置类,在配置类中将驼峰命名法置为true:
@Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
//启用下划线命名和驼峰命名的相互转换
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
三、配置文件版mybatis
1、创建一个mapper接口(interface):注意使用@Mapper或者@MapperScan将接口纳入mybatis管理
// 无论使用注解版还是配置文件版都必须使用@Mapper或者@MapperScan扫描该接口,
// 使其被纳入到Mybatis管理,只有这样Mybatis才会为该接口生成实现
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public int insertEmp(Employee employee);
}
2、编写mybatis的全局配置文件,文件内容可以参考mybatis官方文档(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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
3、编写对应的sql映射文件,可以专门新建一个目录存放该类xml文件(
此处放在mybatis/mapper下),内容如下:mybatis会依据此文件为接口生成实现类
<?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.bdm.springboot.mapper.EmployeeMapper">
<!--public Employee getEmpById(Integer id);-->
<select id="getEmpById" resultType="com.bdm.springboot.bean.Employee">
SELECT * FROM employee WHERE id = #{id}
</select>
<!--public int insertEmp(Employee employee);-->
<insert id="insertEmp">
INSERT INTO employee(lastName,email,gender,d_id) VALUES(#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
namespace的值是mapper接口的全类名,id对应的是接口中的方法名,resultType对应的是接口方法的返回值类型的全类名
4、在application.yml中配置这两类文件的位置信息:
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
5、测试
@RestController
public class EmpController {
@Autowired
EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
public Employee getEmpById(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
}