springboot整合mybatis-plus基于注解实现一对一(一对多)查询功能

时间:2021-12-14 03:32:51

因为目前所用mybatis-plus版本为3.1.1,感觉是个半成品,所有在实体类上的注解只能支持单表,没有一对一和一对多关系映射,且该功能还在开发中,相信mybatis-plus开发团队在不久的将来应该会实现此功能。

由于本人开发习惯的原因,实在是太讨厌大量的xml充斥在整个项目中,尤其是表的mapper.xml,虽然有代码生成器可以生成,但是有些复杂的查询还是需要手写配置文件里的动态sql,这点比较反感(至于为什么反感,也是有多方面原因的)。

不过可能是大量的java开发人员已经被虐惯了,已经习惯各种配置文件,虽然有代码生成器,但是本人觉得,这种不是真正的路子,按理说开源出去的东西让别人用的越简单越爽越好,而不是还需要依赖大量的工具配合才能使用(这个观点仁者见仁智者见智吧)。

因为本人采用的是spring-boot进行开发,本身springboot就提倡采用不用配置自动配置的方式,所以真心希望mybatis(不是mybatis-plus)这点需要继续努力。

基于这点,采用了mybatis-plus里的已经实现好的方法来进行了取巧的操作,废话不多说,直接上代码。

数据库是mysql。

demo的思路是这样的:学生表(Student),学生班级表(StudentClass),在学生的实体类里通过班级Id和班级进行一对一关联,主要通过mapper接口来实现,基于@Results、@Result、@One(或@Many)、@ResultMap这几个mybatis里的注解加上

mybatis-plus里的BaseMapper、QueryWrapper<ChannelEntity>结合起来实现,所以还得写一些代码。

如果mybatis-plus团队把关系映射一并实现注解到实体对象上就能省大量代码了,期待他们早日实现。

pom文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lyb</groupId>
    <artifactId>spring-mybatis-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>spring-mybatis-demo</name>
    <description>Demo project for Spring Boot</description>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <!--
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        -->
 
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.1.1</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

可以看到数据库操作只需依赖mybatis-plus-boot-starter

application.yml文件

?
1
2
3
4
5
6
7
8
9
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: liuyabin
    driver-class-name: com.mysql.jdbc.Driver
mybatis-plus:
  type-aliases-package: com.lyb.springmybatisdemo.entity
  type-aliases-super-type: java.lang.Object

Student实体类代码,可以看到实体类上加上了mybatis-plus的注解,这里也加了@Data lombok的注解为了节省多敲代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.lyb.springmybatisdemo.entity;
 
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
 
@Data
@Builder
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "student")
public class Student {
    @TableId(value = "Id",type = IdType.AUTO)
    private int id;
    @TableField(value = "SName",exist = true,select = true)
    private String name;
    @TableField(value = "Age")
    private int age;
    @TableField(value = "ClassId")
    private int classId;
    @TableField(exist = false)
    private StudentClass studentClass;
}

StudentClass类代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.lyb.springmybatisdemo.entity;
 
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
 
@Data
@Builder
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "stuClass")
public class StudentClass {
    @TableId(value = "ClassId",type = IdType.AUTO)
    private int classId;
    @TableField(value = "ClassName")
    private String className;
}

具体的数据库结构就不放了,参照实体类上注解就很能轻松构建出来,因为就两个表。

StudentClassMapper类代码:

?
1
2
3
4
5
6
7
8
9
package com.lyb.springmybatisdemo.mapper;
 
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lyb.springmybatisdemo.entity.StudentClass;
import org.apache.ibatis.annotations.Mapper;
 
@Mapper
public interface StudentClassMapper extends BaseMapper<StudentClass> {
}

这个mapper很简单,因为mybatis-plus里的BaseMapper已经将基础的单表操作给做了,并且该表没有一对多的需求,如果现实中确实有一对多的需求的话,可以参照下面一对一的方式实现。

StudentMapper代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.lyb.springmybatisdemo.mapper;
 
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lyb.springmybatisdemo.entity.Student;
import org.apache.ibatis.annotations.*;
 
import java.util.List;
 
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
    @Results(id="stuMap",value = {
            @Result(property = "id",column = "Id"),
            @Result(property = "name",column = "SName"),
            @Result(property = "age",column = "Age"),
            @Result(property = "classId",column = "ClassID"),
            @Result(property = "studentClass",column = "ClassID",one = @One(select = "com.lyb.springmybatisdemo.mapper.StudentClassMapper.selectById"))
    })
    @Select("SELECT * FROM STUDENT WHERE ID=#{id}")
    Student findStudentById(int id);
 
    @Select("select * from Student where 1=1 and " +
            "${ew.sqlSegment}")
    @ResultMap(value = "stuMap")
    List<Student> selectStudents(@Param("ew") QueryWrapper<Student> wrapper);
 
 
}

主要关注selectStudents方法的代码。id="stuMap"的@Results里定义了一对一的关系,可以看到有一个@One(select = "com.lyb.springmybatisdemo.mapper.StudentClassMapper.selectById")的定义,该方法并没有在

StudentClassMapper里实现,而是mybatis-plus在BaseMapper里帮我们实现了,那就可以直接方便的拿过来用了,省了我们多谢一个方法的代码了。

selectStudents方法传入的参数QueryWrapper<Student> wrapper可以充分利用lambda来自己构建各种各样的where条件,而且注意该方法的@Select的类SQL的写法,这样不会出错。

接下来是就往两张表里插入多条数据,然后是测试代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.lyb.springmybatisdemo;
 
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyb.springmybatisdemo.entity.Student;
import com.lyb.springmybatisdemo.mapper.StudentMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.List;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringMybatisDemoApplicationTests {
 
    @Autowired
    private StudentMapper studentMapper;
 
 
    @Test
    public  void testByWrapper(){
        QueryWrapper<Student> queryWrapper = new QueryWrapper<Student>();
        queryWrapper.lambda().eq(Student::getAge,2)
                            .eq(Student::getClassId,1);
        List<Student> students = studentMapper.selectStudents(queryWrapper);
    }
}

最后是springboot的启动类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.lyb.springmybatisdemo;
 
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan("com.lyb.springmybatisdemo.mapper")
public class SpringMybatisDemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringMybatisDemoApplication.class, args);
    }
 
}

运行测试类如果按照查询条件插入了多条数据,即年龄是2,班级Id是1的数据,并且班级表里也插入了数据,结果会查询出来,并且结果里Student对象的studentClass属性是已经赋了值的。

到此这篇关于springboot整合mybatis-plus基于注解实现一对一(一对多)查询功能的文章就介绍到这了,更多相关springboot整合mybatis-plus内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/wenwuxianren/p/11032180.html