1. 引入Mybatis的起步依赖
<!--mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
2. 添加数据库驱动坐标
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3. 在application.properties中配置Mybatis的配置信息
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=username
spring.datasource.password=password
4. 创建实体类对象,并编写Mapper
public class User {
private Long id;
private String username;
private String password;
private String name;
//省略getter和setter方法 .. ..
}
//此处的 @Mapper注解是标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
@Mapper
public interface UserMapper {
public List<User> queryUserList();
}
5. 配置Mapper的映射文件,并配置application.properties文件
* 如果使用注解方式的Mybatis,配置已经结束
在resources文件夹下新建mapper文件夹来放置映射文件
例:src\main\resources\mapper\UserMapper.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.itheima.mapper.UserMapper">
<select id="queryUserList" resultType="user">
select * from user
</select>
</mapper>
#spring集成Mybatis环境
#pojo/domain别名扫描包
mybatis.type-aliases-package=com.xxx.domain
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml