整合mybatis
引入mybatis启动器:
mybatis-spring-boot-starter
,这个启动器时mybatis自己实现
springboot提供的starter都是spring-boot-starter-xxx
格式
使用了mybatis启动器之后只需要定义一个
DataSource
即可,它会自动创建使用该DataSource
的SqlSessionFactoryBean
以及SqlSessionTemplate
。并且会自动扫描Mappers
,并关联到SqlSessionTemplate
,然后之策到Spring上下文中,最终就可以使用@AutoWired
注解吧映射接口的实现类注入到指定的地方了。
- 创建springboot项目
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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-boot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--这个启动器是mybatis自己提供的-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>