springboot整合mybatis
1、创建一个基本的Spring Boot项目
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.3.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.linst</groupId>
<artifactId>mybatis-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis-spring-boot</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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.3.0.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、创建一个
IndexController类:
package cn.linst.mybatisspringboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@RequestMapping("/")
String home() {
return "hello world";
}
}
运行访问http://localhost:8080/即可看到输出
3、集成mybatis
1)添加依赖:
pom.xml:
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2)application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-spring-boot
spring.datasource.username=root
spring.datasource.password=
3)先创建一个Country类
在 cn.linst.mybatisspringboot目录下创建一个model,再在在model目录下,Country:
package cn.linst.mybatisspringboot.model;
public class Country {
private Long id;
private String countryname;
private String countrycode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountryname() {
return countryname;
}
public void setCountryname(String countryname) {
this.countryname = countryname;
}
public String getCountrycode() {
return countrycode;
}
public void setCountrycode(String countrycode) {
this.countrycode = countrycode;
}
}
4)添加一个CountryMapper接口
在 cn.linst.mybatisspringboot目录下创建一个mapper,再在mapper目录下创建CountryMapper接口:
package cn.linst.mybatisspringboot.mapper;
import cn.linst.mybatisspringboot.model.Country;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
// 使用了@Mapper 注解
// Spring 启动时会自动扫描该接口,这样就可以在需要使用时直接注入 Mapper 了
@Mapper
public interface CountryMapper {
List<Country> selectAll();
}
5)添加 CountryMapper.xml 映射文件
在src/main/resources 下创建mapper目录,在mapper目录下创建CountryMapper.xml 映射文件:
CountryMapper.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="cn.linst.mybatisspringboot.mapper.CountryMapper">
<select id="selectAll" resultType="cn.linst.mybatisspringboot.model.Country">
select id, countryname, countrycode from country;
</select>
</mapper>
6)配置mybatis
在application.properties 配置文件中添加如下内容:
#映射文件的路径,支持 Ant 风格的通自己符, 多个目己直可以使用英文逗号隔开
mybatis.mapperLocations=classpath:mapper/*.xml
#类型别名包配置,只能指定具体的包,多个配置可以使用英文逗号隔开
mybatis.typeAliasesPackage=cn.linst.mybatisspringboot.model
7)修改引导类MybatisSpringBootApplication
package cn.linst.mybatisspringboot;
import cn.linst.mybatisspringboot.mapper.CountryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MybatisSpringBootApplication implements CommandLineRunner {
@Autowired
private CountryMapper countryMapper;
@Override
public void run(String... args) throws Exception {
System.out.println(countryMapper.selectAll());
}
public static void main(String[] args) {
SpringApplication.run(MybatisSpringBootApplication.class, args);
}
}
运行即可在日志看到输出。
4、mybatis starter配置介绍
Spring Boot 可以通过@ConfigurationProperties 注解自动将配置文件中的属性组装到对象上,这个注解 般都需要配置与属性匹配的前缀,此处前缀为“mybatis ”,因此对MyBat 的配置都是以“mybatis ”作为前缀的。属性类中的字段如果是驼峰形式的,在配置
文件中进行配置时建议改为横杠(-)和小写字母连接的形式,虽然 spring Boot 仍然能正确匹配驼峰形式的属性,但推荐横杠(-)。
如下源码:
package org.mybatis.spring.boot.autoconfigure;
/**
* Configuration properties for MyBatis.
*
* @author Eddú Meléndez
* @author Kazuki Shimizu
*/
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
/**
* Location of MyBatis xml config file.
*/
private String configLocation;
/**
* Locations of MyBatis mapper files.
*/
private String[] mapperLocations;
/**
* Packages to search type aliases. (Package delimiters are ",; \t\n")
*/
private String typeAliasesPackage;
// 省略其他...
/**
* A Configuration object for customize default settings. If {@link #configLocation} is specified, this property is
* not used.
*/
@NestedConfigurationProperty
private Configuration configuration;
}
这个类嵌套了一个Configuration 属性,通过这种方式可以直接对 Configuration 对象进行属性配置。如:
application.properties:
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.aggresive-lazy-loading=true
5、简单示例
1)引入之前的项目
将之前几篇中学习的 leanmybatis项目。通过maven 命令(mvn install )打包到本地仓库或者 将该项目引入当前的工作空间即可。
这里采用引入依赖方式,在pom.xml引入:
<dependency>
<groupId>cn.linst</groupId>
<artifactId>learnmybatis</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
本项目mybatis-spring-boot使用的是@Mapper 注解,对于之前的项目learnmybatis,一个个添加@Mapper注解并不合适。
可以通过一种新的方式来扫描 Mapper 接口。如:
修改引导类:添加@MapperScan
package cn.linst.mybatisspringboot;
import cn.linst.mybatisspringboot.mapper.CountryMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan({"cn.linst.mybatisspringboot.mapper", "cn.linst.learnmybatis.mapper"})
public class MybatisSpringBootApplication implements CommandLineRunner {
@Autowired
private CountryMapper countryMapper;
@Override
public void run(String... args) throws Exception {
System.out.println(countryMapper.selectAll());
}
public static void main(String[] args) {
SpringApplication.run(MybatisSpringBootApplication.class, args);
}
}
2)还需要修改application.properties:让映射文件也扫描到。
#映射文件的路径,支持 Ant 风格的通自己符, 多个目己直可以使用英文逗号隔开
#mybatis.mapperLocations=classpath:mapper/*.xml
mybatis.mapper-locations=classpath:mapper/*.xml,classpath*:cn/linst/**/mapper/*.xml
运行可能报错,因为可能有相同的Spring的bean。
解决方案:
1.要么改bean名
2.要么修改默认的名字生成规则,让它们的名字不重复
如:修改bean名字生成规则。
MapperNameGenerator:
package cn.linst.mybatisspringboot;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.util.ClassUtils;
import java.beans.Introspector;
import java.util.HashMap;
import java.util.Map;
public class MapperNameGenerator implements BeanNameGenerator {
Map<String , Integer> nameMap =new HashMap<String , Integer>();
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
//获取类的名字,如 CountryMapper
String shortClassName = ClassUtils.getShortName(beanDefinition.getBeanClassName());
//将类名转换为规范 变量名,如 countryMapper
String beanName = Introspector.decapitalize(shortClassName);
// 判断名字是否已经存在 ,如存在,则在名字后面增加序号
if (nameMap.containsKey(beanName)) {
int index = nameMap.get(beanName) + 1;
nameMap.put(beanName, index);
//增加序号
beanName += index;
} else {
nameMap.put(beanName, 1);
return beanName;
}
return beanName;
}
}
在引导类:@MapperScan注解中指定 nameGenerator 属性为自定义的生成规则MapperNameGenerator.class 即可。
@SpringBootApplication
@MapperScan(
value = {"cn.linst.mybatisspringboot.mapper", "cn.linst.learnmybatis.mapper"},
nameGenerator = MapperNameGenerator.class
)
public class MybatisSpringBootApplication implements CommandLineRunner {
//...
}
3)开发业务( Service )层
4)开发控制( Controller )层
运行即可。