Spring Boot整合MyBatis步骤:
1. 新建Spring Boot工程,并选择需要使用的技术集
pom.xml文件
<!--引入相对应的starter--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2. 设置相关参数(数据源)
application.yml
#配置相关信息 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver #com.mysql.jdbc.Driver该驱动类过时 url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC username: root password: root
3. 编写一个实体类 Person.java
public class Person { private Integer id; private String name; private String city; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", city='" + city + '\'' + '}'; } }
4. 定义数据层接口与映射配置(两种方式,任意一种都可)
方式一:纯注解开发
@Mapper //SQL映射添加@Mapper注解方便被容器识别 public interface PersonDao { @Select("select * from person where id = #{id}") public Person getById(Integer id); }
方式二:xml开发
新建一个PersonMapper接口
@Mapper public interface PersonMapper { public List<Person> findAll(); }
resources下新建一个mapper文件夹并在里面新建 PersonMapper.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.ityun.springbootstudy.mapper.PersonMapper"> <select id="findAll" resultType="person"> select * from person </select> </mapper>
在application.yml 中添加MyBatis配置
#MyBatis配置 mybatis: mapper-locations: classpath:mapper/*Mapper.xml #mapper映射文件路径 type-aliases-package: com.ityun.springbootstudy.domain #定义实体类的别名
5. 测试类中注入dao接口,测试功能
@SpringBootTest class SpringbootStudyApplicationTests { @Autowired private PersonDao personDao; @Autowired private PersonMapper personMapper; @Test public void findTest() { System.out.println(personDao.getById(1)); } @Test public void findAllTest(){ List<Person> list = personMapper.findAll(); System.out.println(list); } }
6. 运行结果