当前位置:   article > 正文

springboot整合mybatis以及mybatis-plus 开发_springboot+mybatisplus接口开发步骤

springboot+mybatisplus接口开发步骤

一、springboot整合mybatis

1.注解版
1.1 导入坐标
  1. <dependencies>
  2. <!--mybatis坐标-->
  3. <dependency>
  4. <groupId>org.mybatis.spring.boot</groupId>
  5. <artifactId>mybatis-spring-boot-starter</artifactId>
  6. <version>2.2.2</version>
  7. </dependency>
  8. <!--mysql-->
  9. <dependency>
  10. <groupId>mysql</groupId>
  11. <artifactId>mysql-connector-java</artifactId>
  12. <version>8.0.29</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-web</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-test</artifactId>
  21. <scope>test</scope>
  22. </dependency>
  23. </dependencies>
1.2 编写配置文件application.yml
  1. #数据源
  2. spring:
  3. datasource:
  4. username: root
  5. password: 123456
  6. url: jdbc:mysql://localhost:3307/testdb?serverTimezone=GMT
  7. driver-class-name: com.mysql.cj.jdbc.Driver
1.3 准备实体类Account ,省略了有参无参 setter getter toString方法
  1. public class Account {
  2. private int aid;
  3. private String aname;
  4. private int amoney;
  5. }
1.4 编写mapper映射器接口

@Mapper//注册注入一个mapper

@MapperScan(basePackages ="com.ztt.mybatis_springboot.mapper")//注册注入多个mapper(以包为单位) )

注意:两者只能写一个

  1. //@Mapper//注册注入一个mapper
  2. public interface AccountMapper {
  3. @Select("select * from account")
  4. public List<Account> findAll();
  5. }
1.5 编写测试类
  1. @SpringBootTest
  2. class MybatisSpringbootApplicationTests {
  3. @Autowired(required = false)
  4. AccountMapper accountMapper;
  5. @Test
  6. void contextLoads() {
  7. List<Account> all=accountMapper.findAll();
  8. for (int i = 0; i <all.size() ; i++) {
  9. Account account=all.get(i);
  10. System.out.println(account);
  11. }
  12. }
  13. }
1.6 输出结果

2.xml版
2.1 在接口中定义一个方法
public List<Account> find();
2.2 编写xml文件,在resources目录下新建一个mapper包,在mapper包里面新建一个AccountMapper.xml文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.ztt.mybatis_springboot.mapper.AccountMapper">
  4. <select id="find" resultType="com.ztt.mybatis_springboot.pojo.Account">
  5. select * from account;
  6. </select>
  7. </mapper>
2.3 在主配置文件中添加mybatis的配置
  1. mybatis:
  2. mapper-locations: mappers/*.xml
2.4 编写测试类
  1. @Test
  2. void contextLoads1() {
  3. List<Account> all=accountMapper.find();
  4. for (int i = 0; i <all.size() ; i++) {
  5. Account account=all.get(i);
  6. System.out.println(account);
  7. }
  8. }
2.5 输出结果

二、MyBatis-Plus

1.MyBatis-Plus介绍

        MyBatis最佳搭档,只做增强不做改变,为简化开发、提高效率而生。

        详细信息请看官方文档https://www.wpsshop.cn/w/笔触狂放9/article/detail/1011741

推荐阅读
相关标签
  

闽ICP备14008679号