当前位置:   article > 正文

Mybatis_springboot与mybatis-plus_mybatis-spring-boot-starter 和 mybatis

mybatis-spring-boot-starter 和 mybatis

一 Mybatis_springboot

MyBatis 是一个流行的持久层框架,可以与 Spring Boot 无缝集成。下面是如何在 Spring Boot 项目中使用 MyBatis 的基本步骤。

1. 创建 Spring Boot 项目

你可以使用 Spring Initializr 创建一个新的 Spring Boot 项目。选择以下依赖项:

  • Spring Web
  • MyBatis Framework
  • 数据库(如 H2、MySQL、PostgreSQL 等)

2. 添加依赖

如果你已经创建了项目,可以在 pom.xml(对于 Maven 项目)中添加 MyBatis 和数据库的依赖。例如对于 MySQL:

  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.28</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>

3. 数据库配置

在 application.yml 或 application.properties 文件中配置 数据库连接信息。例如,如果使用 MySQL,可以这么配置:

  1. #数据源
  2. spring:
  3. datasource:
  4. username: root
  5. password: 123456
  6. url: jdbc:mysql://localhost:3306/myschool?serverTimezone=GMT
  7. driver-class-name: com.mysql.cj.jdbc.Driver

4. 创建数据模型

创建一个 Java 类,表示数据库表的结构。例如:

  1. package com.xn.mybatis_springboot.pojo;
  2. /**
  3. * @author 许娜
  4. * @version 1.0
  5. * @since 2024/8/13
  6. */
  7. public class Account {
  8. private int aid;
  9. private String aname;
  10. private int amoney;
  11. @Override
  12. public String toString() {
  13. return "Account{" +
  14. "aid=" + aid +
  15. ", aname='" + aname + '\'' +
  16. ", amoney=" + amoney +
  17. '}';
  18. }
  19. public Account(int aid, String aname, int amoney) {
  20. this.aid = aid;
  21. this.aname = aname;
  22. this.amoney = amoney;
  23. }
  24. public Account() {
  25. }
  26. public int getAid() {
  27. return aid;
  28. }
  29. public void setAid(int aid) {
  30. this.aid = aid;
  31. }
  32. public String getAname() {
  33. return aname;
  34. }
  35. public void setAname(String aname) {
  36. this.aname = aname;
  37. }
  38. public int getAmoney() {
  39. return amoney;
  40. }
  41. public void setAmoney(int amoney) {
  42. this.amoney = amoney;
  43. }
  44. }

5. 创建 Mapper 接口

创建 MyBatis 的 Mapper 接口,用于定义 SQL 操作。例如:

  1. //@Mapper//注册注入一个mapper
  2. public interface AccountMapper {
  3. @Select("select * from account")
  4. public List<Account> findAll();
  5. }

或 

  1. @SpringBootApplication
  2. @MapperScan(basePackages="com.xn.mybatis_springboot.mapper")//注册注入多个mapper(以包为单位)
  3. public class MybatisSpringbootApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(MybatisSpringbootApplication.class, args);
  6. }
  7. }

6.测试

  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. }


mybatis-plus

1.坐标

     <dependency>
         <groupId>com.baomidou</groupId>
         <artifactId>mybatis-plus-boot-starter</artifactId>
         <version>3.1.1</version>
     </dependency>
    注意:mp坐标添加后,mybatis坐标移除

  1. <!-- mybatisPlus坐标 -->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>3.1.1</version>
  6. </dependency>
  7. <!-- mybatis坐标 -->
  8. <!-- <dependency>-->
  9. <!-- <groupId>org.mybatis.spring.boot</groupId>-->
  10. <!-- <artifactId>mybatis-spring-boot-starter</artifactId>-->
  11. <!-- <version>2.2.2</version>-->
  12. <!-- </dependency>-->
  13. <!-- mysql -->

2.编写注解配置实体类与关系表映射关系(truncate清空表以及主键)

    @TableName(value = "关联表名称")=========================》修饰在类
    @TableField(value = "关联字段名称")======================》修饰在属性
                exist = "忽略字段"
    @TableId(type="指定主键生成策略,默认雪花算法")=============》修饰在属性
                AUTO(0),
                NONE(1),
                INPUT(2),
                ASSIGN_ID(3),
                ASSIGN_UUID(4);

  1. @TableName("account")
  2. public class Account {
  3. @TableId(value = "aid",type= IdType.AUTO)
  4. private int aid;
  5. @TableField("aname")
  6. private String aname;
  7. @TableField("amoney")
  8. private int amoney;
  9. }

3.使用

    BaseMapper===========》公共的数据访问层


    IService/ServiceImp==》公共的业务层

4.配置yml文件

  1. #数据源
  2. spring:
  3. datasource:
  4. username: root
  5. password: 123456
  6. url: jdbc:mysql://localhost:3306/myschool?serverTimezone=GMT
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. mybatis:
  9. mapper-locations: mappers/*.xml
  10. mybatis-plus:
  11. configuration:
  12. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

5.测试代码使用

(1)新增

  1. @SpringBootTest
  2. public class Test01 {
  3. @Autowired(required = false)
  4. AccountMapper accountMapper;
  5. //新增
  6. @Test
  7. public void show1(){
  8. Account account = new Account("夕夕",2000);
  9. int row = accountMapper.insert(account);
  10. System.out.println("主键回填id:"+account.getAid());
  11. System.out.println("影响行数:"+row);
  12. }
  13. }

 

(2) 修改

  1. @SpringBootTest
  2. public class Test01 {
  3. @Autowired(required = false)
  4. AccountMapper mapper;
  5. //修改ID
  6. @Test
  7. public void test02()throws Exception{
  8. Account account = new Account(3,"发发",5000,1,"干饭");
  9. int row = mapper.updateById(account);
  10. System.out.println("影响行数:"+row);
  11. }
  12. //
  13. // //修改Name
  14. @Test
  15. public void test03()throws Exception{
  16. //1.修改数据
  17. Account account = new Account();
  18. account.setAhobby("打架");
  19. //2.创建条件
  20. QueryWrapper<Account> wrapper = new QueryWrapper<Account>();
  21. wrapper.eq("aname","毛毛");
  22. mapper.update(account,wrapper);
  23. }
  24. }

 

(3) mp分页使用

注意:
  1.page.setCurrent(2);当前页码从1开始
  2.分页需要配置插件
  3.mp坐标版本3.1.1不能使用过高版本

  1. <!-- mybatisPlus坐标 -->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>3.4.3</version>
  6. </dependency>
  1. @Configuration
  2. public class MyBatisPlusConfig {
  3. //注入mp拦截器
  4. @Bean
  5. public MybatisPlusInterceptor mybatisPlusInterceptor(){
  6. //1.实例化拦截器
  7. MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
  8. //2.分页拦截器
  9. mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
  10. return mybatisPlusInterceptor;
  11. }
  12. }
  1. /**
  2. * mp分页使用
  3. * 注意:
  4. * 1.page.setCurrent(2);当前页码从1开始
  5. * 2.分页需要配置插件
  6. * 3.mp坐标版本3.1.1不能使用过高版本
  7. * */
  8. @Test
  9. public void test08()throws Exception{
  10. //1.定义分页规则
  11. Page<Account> page = new Page<Account>();
  12. page.setSize(3);//每页记录数
  13. page.setCurrent(2);//当前页码
  14. //2.查询条件(可选)
  15. QueryWrapper queryWrapper = new QueryWrapper();
  16. queryWrapper.eq("ahobby","唱歌");
  17. IPage<Account> iPage = mapper.selectPage(page,null);
  18. List<Account> list = iPage.getRecords();//分页结果
  19. System.out.println("总记录数:"+iPage.getTotal());
  20. System.out.println("总记页数:"+iPage.getPages());
  21. for (int i = 0; i < list.size(); i++) {
  22. Account account = list.get(i);
  23. System.out.println(account);
  24. }
  25. }

(4)查询

        普通查询

  1. //查询ID
  2. @Test
  3. public void test04()throws Exception{
  4. Account account = mapper.selectById(5);
  5. System.out.println(account);
  6. }
  7. //
  8. //查询IDS
  9. @Test
  10. public void test05()throws Exception{
  11. List<Account> list = mapper.selectBatchIds(Arrays.asList(5,1,3));
  12. for (int i = 0; i < list.size(); i++) {
  13. Account account = list.get(i);
  14. System.out.println(account);
  15. }
  16. }

 

        QueryWrapper 

QueryWrapper 是 MyBatis-Plus 中常用的一个工具类,用于构建 SQL 查询条件的方式。它提供了链式调用的方法来设置查询条件,使得代码更加简洁、易读。

  1. //查询count
  2. @Test
  3. public void test06()throws Exception{
  4. int count = mapper.selectCount(null);
  5. System.out.println(count);
  6. }
  7. //查询list
  8. @Test
  9. public void test07()throws Exception{
  10. QueryWrapper<Account> queryWrapper = new QueryWrapper();
  11. // queryWrapper.eq("aage","11");
  12. // queryWrapper.eq("ahobby","唱歌");
  13. queryWrapper.eq("ahobby","唱歌").or().eq("aage","11");
  14. List<Account> list = mapper.selectList(queryWrapper);
  15. for (int i = 0; i < list.size(); i++) {
  16. Account account = list.get(i);
  17. System.out.println(account);
  18. }
  19. }

        LambdaQueryWrapper
  1. @Test
  2. public void show1(){
  3. //1.查询条件
  4. LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<Account>();
  5. lambdaQueryWrapper.gt(Account::getAage,12);
  6. //2.查询
  7. List<Account> list = mapper.selectList(lambdaQueryWrapper);
  8. for (int i = 0; i < list.size(); i++) {
  9. Account account = list.get(i);
  10. System.out.println(account);
  11. }
  12. }

         模拟动态查询

  1. //模拟动态查询1
  2. @Test
  3. public void show2(){
  4. //1.前端发送来的数据
  5. Integer num1 = null;
  6. Integer num2 = 15;
  7. //1.查询条件
  8. LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<Account>();
  9. //2.判断
  10. if(null != num2){
  11. lambdaQueryWrapper.lt(Account::getAage,num2);
  12. }
  13. if(null != num1){
  14. lambdaQueryWrapper.gt(Account::getAage,num1);
  15. }
  16. //3.查询
  17. List<Account> list = mapper.selectList(lambdaQueryWrapper);
  18. for (int i = 0; i < list.size(); i++) {
  19. Account account = list.get(i);
  20. System.out.println(account);
  21. }
  22. }
  23. //模拟动态查询2
  24. @Test
  25. public void show3(){
  26. //1.前端发送来的数据
  27. Integer num1 = null;
  28. Integer num2 = 15;
  29. //1.查询条件
  30. LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<Account>();
  31. //2.判断
  32. lambdaQueryWrapper.lt(null != num2,Account::getAage,num2);
  33. lambdaQueryWrapper.gt(null != num1,Account::getAage,num1);
  34. //3.查询
  35. List<Account> list = mapper.selectList(lambdaQueryWrapper);
  36. for (int i = 0; i < list.size(); i++) {
  37. Account account = list.get(i);
  38. System.out.println(account);
  39. }
  40. }

        投影查询-字段查询 

  1. //投影查询-字段查询
  2. @Test
  3. public void show4() {
  4. //1.条件
  5. LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<Account>();
  6. lambdaQueryWrapper.select(Account::getAname,Account::getAhobby);
  7. //2.查询
  8. List<Account> list = mapper.selectList(lambdaQueryWrapper);
  9. //4.遍历
  10. for (int i = 0; i < list.size(); i++) {
  11. Account account = list.get(i);
  12. System.out.println(account);
  13. }
  14. }

(5)删除 

逻辑删除:

为数据设置是否可用状态字段,删除时设置状态字段为不可用状态, 数据保留在数据库中,执行的是update操作

实现步骤:

         步骤1:修改数据库表添加`deleted`列,比如`0`代表正常,`1`代表删除,可以在添加列的同时                  设置其默认值为`0`正常。

        步骤2:实体类添加属性以及注解 @TableLogic(value="0",delval="1") private Integer deleted;                     value为正常数据的值,delval为删除数据的值 逻辑删除

  1. //查询delete
  2. @Test
  3. public void test09()throws Exception{
  4. mapper.deleteById(4);
  5. }

 物理删除:

业务数据从数据库中丢弃,执行的是delete操作

  1. //查询delete
  2. @Test
  3. public void test09()throws Exception{
  4. mapper.deleteById(3);
  5. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/1009452
推荐阅读
相关标签
  

闽ICP备14008679号