0


「Spring Boot 系列」08. Spring Boot整合MyBatis

在这里插入图片描述

目录

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

publicclassPerson{privateInteger id;privateString name;privateString city;publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicStringgetCity(){return city;}publicvoidsetCity(String city){this.city = city;}@OverridepublicStringtoString(){return"Person{"+"id="+ id +", name='"+ name +'\''+", city='"+ city +'\''+'}';}}

4. 定义数据层接口与映射配置(两种方式,任意一种都可)

  • 方式一:纯注解开发
@Mapper//SQL映射添加@Mapper注解方便被容器识别publicinterfacePersonDao{@Select("select * from person where id = #{id}")publicPersongetById(Integer id);}
  • 方式二:xml开发
  1. 新建一个PersonMapper接口
@MapperpublicinterfacePersonMapper{publicList<Person>findAll();}
  1. resources下新建一个mapper文件夹并在里面新建 PersonMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.ityun.springbootstudy.mapper.PersonMapper"><selectid="findAll"resultType="person">
        select * from person
    </select></mapper>
  1. 在application.yml 中添加MyBatis配置
#MyBatis配置mybatis:mapper-locations: classpath:mapper/*Mapper.xml#mapper映射文件路径type-aliases-package: com.ityun.springbootstudy.domain #定义实体类的别名

5. 测试类中注入dao接口,测试功能

@SpringBootTestclassSpringbootStudyApplicationTests{@AutowiredprivatePersonDao personDao;@AutowiredprivatePersonMapper personMapper;@TestpublicvoidfindTest(){System.out.println(personDao.getById(1));}@TestpublicvoidfindAllTest(){List<Person> list = personMapper.findAll();System.out.println(list);}}

6. 运行结果

在这里插入图片描述在这里插入图片描述


本文转载自: https://blog.csdn.net/weixin_52986315/article/details/125696828
版权归原作者 郭尕 所有, 如有侵权,请联系我们删除。

“「Spring Boot 系列」08. Spring Boot整合MyBatis”的评论:

还没有评论