官方说明:MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
在 pom.xml 中 ,使用 Spring Boot 2.0 相关依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
添加 web 和 jdbc,mybatis 依赖
<dependencies>
<!-- Web模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- 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>1.3.2</version>
</dependency>
</dependencies>
# sql config
spring.datasource.url=jdbc:mysql://192.168.158.178:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=147258369..
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#mybatis cache 配置 false xml中支持cache也无效
mybatis.configuration.cache-enabled=false
SpringBoot会自动加载<font color="#FF7f00">spring.datasource.*</font>相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。
在启动类中添加对mapper包扫描<font color="#FF0000">@MapperScan</font>
/**
* @author log.r
*/
@SpringBootApplication
@EnableCaching
@MapperScan("com.whh.spring.boot.dao")
public class SpringBoot2Application {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(SpringBoot2Application.class);
logger.info(">>>>> spring-boot 正在启动 <<<<<");
SpringApplication.run(SpringBoot2Application.class, args);
logger.info(">>>>> spring-boot 启动完成 <<<<<");
}
}
或者直接在Mapper类上面添加注解@Mapper,建议使用上面那种,不然每个<font color="#FF7700">mapper</font>加个注解也挺麻烦的
可以使用 generator-plugin 生成 mapper.xml mapper.java和实体对象。