1.在原有的依赖中,添加MyBatis的依赖
<!--SpringBoot整合MyBatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2.配置相关数据源信息(application.yml)。
#DataBase Configuration
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springbootdemo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username: root
password: 123
#SpringDataJPA Configuration
jpa:
database: mysql
show-sql: true
generate-ddl: true
3.创建实体类,对应数据库表中的字段,并添加getter、setter和toString方法
4.创建mapper接口和对应的sql映射文件,二者在同一个包下。
MyUserMapper :
package com.gxh.mapper; import com.gxh.entity.MyUser; import java.util.List; public interface MyUserMapper { List<MyUser> getUserList(); }
MyUserMapper .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="com.gxh.mapper.MyUserMapper"> <select id="getUserList" resultType="com.gxh.entity.MyUser"> select * from user </select> </mapper>
5.在SpringBoot启动类上添加@MapperScan注解
6.运行,会报500错误,
解决办法:
方法1:将mapper.xml建在resources目录下,和mapper类在同一目录结构下。
方法2:在pom.xml中添加下面代码
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
再次运行,会发现,可以出现数据了