SpringBoot整合mybatis步骤(详细)

SpringBoot整合mybatis步骤

  1. 创建SpringBoot工程
  2. 在pom文件中导入mybatis相关的依赖
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.25</version>
    <scope>runtime</scope>
</dependency>
<!--springboot整合mybatis的依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
</dependency>
<!--添加mybatis分页插件支持 根据需求可要可不要-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.0.0</version>
</dependency>

  1. 在SpringBoot配置文件中定义数据源,并整合mybatis相关的配置
#定义数据源组件  
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/userdb?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123

#springboot整合mybatis的配置
#指定mybatis的配置文件(将mybatis配置文件复到resources目录下mybatis中根据自己的需求在mybatis配置文件中添加自己的配置)
mybatis.config-location=classpath:mybatis/mybatis-config.xml

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>

	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
	</plugins>
	</environments>-->

	 <!--加载sql映射文件-->
	<!--<mappers>
		<package name="com.gulo.mapper.*xml"></package>
	</mappers>-->

</configuration>

  1. 记得在SpringBoot启动类上添加mapper接口扫描注解
@SpringBootApplication
//添加扫描mybatis的dao层接口,生成实现类
@MapperScan(value = "com.baidu.mapper")
public class Sbdemo2Application {
    public static void main(String[] args) {
        SpringApplication.run(Sbdemo2Application.class, args);
    }
}

你可能感兴趣的:(Java)