编程技术是改变世界的力量。
本站
当前位置:网站首页 > 后端语言 > 正文

Java,MyBatis,基于注解方式和基于XML配置,一对多,应用案例

gowuye 2024-04-04 11:54 6 浏览 0 评论

工程:

SpringBoot+MyBatis

<dependencies>
    <!-- SpringBoot==>Web依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- SpringBoot==>健康监控-->
    <!--
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    -->
    <!-- SpringBoot==>面向切面-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <!-- SpringBoot==>参数校验-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <!-- SpringBoot==>缓存抽象-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- SpringBoot==>安全管理-->
    <!--
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    -->
    <!-- SpringBoot==>单元测试-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--mybatis-plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.1</version>
    </dependency>
    <!--mybatis-plus代码生成器-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.4.1</version>
    </dependency>
    <!-- pagehelper分页 -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.11</version>
    </dependency>
    <!--
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.13</version>
    </dependency>
    -->
    <dependency>
        <groupId>com.github.jsqlparser</groupId>
        <artifactId>jsqlparser</artifactId>
        <version>3.1</version>
    </dependency>
    <!-- Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- Druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.22</version>
    </dependency>
    <!-- commons.lang3-->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.7</version>
    </dependency>
    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.73</version>
    </dependency>
    <!-- JUnit测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!-- lombok插件-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

SQL脚本

CREATE TABLE `dept` (
	`id` INT(12) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
	PRIMARY KEY (`id`) USING BTREE
)
COMMENT='部门表',COLLATE='utf8_unicode_ci',ENGINE=InnoDB;

CREATE TABLE `emp` (
	`id` INT(12) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NULL DEFAULT NULL COLLATE ''utf8_unicode_ci'',
	`email` VARCHAR(100) NULL DEFAULT NULL COLLATE ''utf8_unicode_ci'',
	`gender` VARCHAR(100) NULL DEFAULT NULL COLLATE ''utf8_unicode_ci'',
	`age` INT(12) NULL DEFAULT NULL,
	`create_time` TIMESTAMP NULL DEFAULT NULL,
	`dept_id` INT(11) NULL DEFAULT NULL,
	PRIMARY KEY (`id`) USING BTREE
)
COMMENT='员工表',COLLATE='utf8_unicode_ci',ENGINE=InnoDB;

基于注解方式

Model:

package com.what21.demo01.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.List;

@Data
@TableName("dept")
public class Dept {

    // ID
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    // 名称
    private String name;
    // 部门下的员工
    private List<Employee> employeeList;

}
package com.what21.demo01.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

@Data
@TableName("emp")
public class Employee {

    // ID
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    // 名称
    private String name;
    // 邮箱
    private String email;
    // 性别
    private String gender;
    // 年龄
    private Integer age;
    // 创建时间
    private Date createTime;
    // 所属部门
    private Dept dept;

}

Mapper:

package com.what21.demo01.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.what21.demo01.model.Dept;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Repository
public interface DeptMapper extends BaseMapper<Dept> {

    @Results(id = "deptMap", value = {
            @Result(column = "id", property = "id", id = true),
            @Result(column = "name", property = "name")
    })
    @Select("select * from dept where id=#{id}")
    public Dept getById(@Param("id") Integer id);


}
package com.what21.demo01.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.what21.demo01.model.Employee;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface EmployeeMapper extends BaseMapper<Employee> {

    @Select("select * from emp")
    @Results(id = "employeeMap", value = {
            @Result(column = "id", property = "id", id = true),
            @Result(column = "name", property = "name"),
            @Result(column = "email", property = "email"),
            @Result(column = "gender", property = "gender"),
            @Result(column = "age", property = "age"),
            @Result(column = "dept_id", property = "dept"
                    , one = @One(select = "com.what21.demo01.mapper.DeptMapper.getById",
                    fetchType = FetchType.LAZY))
    })
    public List<Employee> getAll();

}

测试:

package com.what21.demo01.tester;

import com.what21.demo01.mapper.EmployeeMapper;
import com.what21.demo01.model.Employee;
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 EmployeeMapperTester {

    @Autowired
    EmployeeMapper employeeMapper;

    @Test
    public void testList() {
        List<Employee> beanList = employeeMapper.getAll();
        beanList.forEach(employee -> {
            System.out.print(employee);
            System.out.println(",所属部门:" + employee.getDept());
        });
    }

}

基于XML配置

Model:

package com.what21.demo02.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.List;

@Data
@TableName("dept")
public class Dept {

    // ID
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    // 名称
    private String name;
    // 部门下的员工
    private List<Employee> employeeList;

}
package com.what21.demo02.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

@Data
@TableName("emp")
public class Employee {

    // ID
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    // 名称
    private String name;
    // 邮箱
    private String email;
    // 性别
    private String gender;
    // 年龄
    private Integer age;
    // 创建时间
    private Date createTime;
    // 所属部门
    private Dept dept;

}

Mapper

package com.what21.demo02.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.what21.demo02.model.Dept;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository("deptMapper2")
public interface DeptMapper extends BaseMapper<Dept> {

    public Dept getById(@Param("id") Integer id);

}
package com.what21.demo02.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.what21.demo02.model.Employee;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("employeeMapper2")
public interface EmployeeMapper extends BaseMapper<Employee> {

    public List<Employee> getAll();

}

Mapper映射文件

DeptMapper.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.what21.demo02.mapper.DeptMapper">

    <resultMap id="deptResultMap" type="com.what21.demo02.model.Dept">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
    </resultMap>

    <select id="getById" parameterType="int" resultMap="deptResultMap">
        select * from `dept` where id=#{id}
    </select>

</mapper>

EmployeeMapper.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.what21.demo02.mapper.EmployeeMapper">

    <resultMap id="employeeResultMap" type="com.what21.demo02.model.Employee">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="email" property="email"/>
        <result column="gender" property="gender"/>
        <result column="age" property="age"/>
        <result column="create_time" property="createTime"/>
        <collection property="dept" column="dept_id" select="com.what21.demo02.mapper.DeptMapper.getById"/>
    </resultMap>

    <select id="getAll" resultMap="employeeResultMap">
        select * from `emp`
    </select>

</mapper>

测试:

package com.what21.demo02.tester;

import com.what21.demo02.mapper.EmployeeMapper;
import com.what21.demo02.model.Employee;
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.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmployeeMapperTester {

    @Resource(name = "employeeMapper2")
    EmployeeMapper employeeMapper;

    @Test
    public void testList() {
        List<Employee> beanList = employeeMapper.getAll();
        beanList.forEach(employee -> {
            System.out.print(employee);
            System.out.println(",所属部门:" + employee.getDept());
        });
    }

}

启动类

package com.what21;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(
        exclude = {
                org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
        }
)
@MapperScan(basePackages = {"com.what21.demo01.mapper", "com.what21.demo02.mapper"})
public class MyBatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyBatisApplication.class, args);
    }

}

相关推荐

爱上开源之golang入门至实战第四章-切片(Slice)

前言Go数组的长度不可改变,在特定场景中这样的集合就不太适用,Go中提供了一种灵活,功能强悍的内置类型切片("动态数组"),与数组相比切片的长度是不固定的,可以追加元素,在追加时可...

Go语言入门必知教程-切片

切片是一种灵活的和可扩展的数据结构,用于实现和管理数据集。切片由多个元素组成,所有元素都是相同类型的。切片是动态数组的一部分,可以根据需要进行增长和收缩。与数组一样,切片也可以索引。切片具有容量和长度...

Go语言基础-切片

切片是什么?切片是Go语言的一种数据结构。和数组相似,不过切片可以在它的结尾增加更多的元素。这样可变长度在实际编程中更为有用。声明切片切片的声明和数组也很相似,只是声明切片时不需要指定大小。例:va...

5分钟掌握GO中切片的基本使用方法

最近Golang越来越火,不少小伙伴都纷纷开始学习Golang,但对于原先为C++或者JAVA的同学,用习惯了数据、list、vector等,会对Go的切片slice不习惯,下面整理出go中slice...

揭秘 Go 切片(Slice)的秘密

当向切片添加新参数时,底层数组会发生什么变化?它会扩展以容纳更多元素吗?在这篇文章中,我们将深入探讨切片的内部工作原理,以及如何利用这些知识来进行更好的内存管理和性能优化。具体而言,我们将探索Go...

【Go语言slice详解】深入掌握Go语言中的slice类型及常用操作!

Go语言中的slice(切片)是一种非常方便的数据结构,可以动态地增加或减少其元素数量,且可以访问底层数组的任意一个子序列。本文将对Go语言中的slice进行详细的讲解。Slice的定义在Go语言中,...

掌握GO中的Slice,这就够了

最近Golang越来越火,不少小伙伴都纷纷开始学习Golang,但对于原先为C++或者JAVA的同学,用习惯了数据、list、vector等,会对Go的切片slice不习惯,下面整理出go中slice...

golang2021面向对象(26)Go语言类型内嵌和结构体内嵌

结构体可以包含一个或多个匿名(或内嵌)字段,即这些字段没有显式的名字,只有字段的类型是必须的,此时类型也就是字段的名字。匿名字段本身可以是一个结构体类型,即结构体可以包含内嵌结构体。?可以粗略地将这个...

2022-11-13:以下go语言代码中,如何获取结构体列表以及结构体内

2022-11-13:以下go语言代码中,如何获取结构体列表以及结构体内的指针方法列表?以下代码应该返回{"S1":["M1","M2"],"S...

Go语言文件和目录操作

文件和目录操作概述一、文件和目录操作概述在计算机中,文件和目录是存储数据的重要方式。在Go语言中,我们可以使用os和io/ioutil包提供的函数和结构体来进行文件和目录操作。本文将详细介绍Go语言中...

跟我一起学习go语言(五)golang中结构体的初始化方法

1、自定义一个结构体typeVertexstruct{X,Yfloat64}2、初始化方法-指针:rect1:=new(Vertex)rect2:=&Vertex...

Go复合数据类型:结构体

一种通用的、对实体对象进行聚合抽象的能力,在Go中,提供这种聚合抽象能力的类型是结构体类型,也就是struct。自定义一个新类型在Go中,我们自定义一个新类型一般有两种方法。第一种是类型定义...

Go语言基础:方法

导读在阅读本文章前,假定你具备如下能力:?已掌握结构体1.方法1.1方法的概念在理解程序中方法的概念时,我们先看看现实中的一些情况,这样相对比较好理解一些。在农村的朋友可能会知道,在医疗落后的情况...

为什么 Go 语言 struct 要使用 tags

在Go语言中,struct是一种常见的数据类型,它可以用来表示复杂的数据结构。在struct中,我们可以定义多个字段,每个字段可以有不同的类型和名称。除了这些基本信息之外,Go还提供了s...

一文带你掌握掌握 Golang结构体与方法

1.Golang结构体的概念及定义结构体是Golang中一种复合类型,它是由一组具有相同或不同类型的数据字段组成的数据结构。结构体是一种用户自定义类型,它可以被用来封装多个字段,从而实现数据的...

取消回复欢迎 发表评论: