[Mybatis] Mybatis handles one-to-many, many-to-many relationship mapping-four

chatting part

In the previous article, we talked about several ways of ORM mapping in Mybatis. Related articles:
[Mybatis] Simple introduction and tool class encapsulation - 1
[Mybatis] How to implement ORM mapping - 2
[Mybatis] Dynamic SQL and caching mechanism of Mybatis - 3

In this article, let's talk about how Mybatis handles one-to-one, one-to-many, and many-to-many relationship mapping

First create the environment, the table structure

create database `mybatis-wx-demo` character set 'utf8mb4';
use `mybatis-wx-demo`;
create table user
(
    id int primary key auto_increment comment '主键id',
    user_name varchar(255) comment '用户名',
    age int comment '年龄',
    create_time datetime comment '创建时间'
) comment '用户表';

insert into user values (1, '全栈小白', 23, CURRENT_TIMESTAMP()),
                        (2, '南宫飞雪', 25, CURRENT_TIMESTAMP()),
                        (3, '盒马鲜生', 30, CURRENT_TIMESTAMP());

create table user_account(
    acc_id int primary key auto_increment comment '账户id',
    acc_balance int default 0 comment '账户余额',
    user_id int comment '用户id'
) comment '用户账户表';
insert into user_account values (1, 100, 1);

create table role(
     role_id int primary key auto_increment comment '角色id',
     role_name varchar(50) comment '角色名'
) comment '角色表';

insert into role values (1, '超级管理员'), (2, '管理员'), (3, '用户');

create table user_role(
     id int primary key auto_increment comment '主键id',
     u_id int not null comment '用户id',
     r_id int not null comment '角色id'
) comment '用户角色关联表';

insert into user_role values (1, 1, 1), (2, 1, 2);

create table user_photo(
    id int primary key auto_increment comment '主键',
    user_id int not null comment '用户id',
    url varchar(255) not null comment '用户照片'
) comment '用户照片表';
insert into user_photo values (1, 1, 'https://img2.baidu.com/it/u=3202947311,1179654885&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500'),
                              (2, 1, 'https://lmg.jj20.com/up/allimg/1114/040221103339/210402103339-8-1200.jpg');

Talk about the table structure, user and user_account are one-to-one relationship, the user can only have one account,

The relationship between user and user_photo is one-to-many, and users can have multiple life photos

User and role are in a many-to-many relationship, a user can have multiple roles

Closer to home

The entity class relationship will not be demonstrated, focusing on data encapsulation

Requirement 1: Query user information and user account information with user id 1 (one-to-one)

1. Create a UserAccountInfoBO business encapsulation object

/**
 * @Project: mybatis-wx-demo
 * @Author: [email protected]
 * @Create: 2023/3/10 11:01
 * @Description:
 **/
@Data
public class UserAccountInfoBO {
    
    

    private User userInfo;
    private UserAccount userAccountInfo;
}

2. Write the interface

/**
 * @Project: mybatis-wx-demo
 * @Author: [email protected]
 * @Create: 2023/2/28 10:41
 * @Description:
 **/
public interface UserMapper {
    
    
    UserAccountInfoBO selectUserAndAccountByUserId(@Param("id") Integer id);
}

3. Write the xml configuration file

Use the association tag to handle complex javaBean

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace = 所需实现的接口全限定名-->
<mapper namespace="com.cxs.mapper.UserMapper">
    <resultMap id="selectUserAndAccountByUserIdMap" type="com.cxs.bo.UserAccountInfoBO">
        <association property="userInfo" javaType="com.cxs.model.User">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="userName" column="user_name" jdbcType="VARCHAR"/>
            <result property="age" column="age" jdbcType="INTEGER"/>
            <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        </association>
        <association property="userAccountInfo" javaType="com.cxs.model.UserAccount">
            <id property="accId" column="acc_id" jdbcType="INTEGER"/>
            <result property="accBalance" column="acc_balance" jdbcType="INTEGER"/>
            <result property="userId" column="user_id" jdbcType="INTEGER"/>
        </association>
    </resultMap>
    <select id="selectUserAndAccountByUserId" resultMap="selectUserAndAccountByUserIdMap" parameterType="java.lang.Integer">
        select *
           from user u
           inner join user_account ua
           on u.id = ua.user_id
        where u.id = #{id}
    </select>
</mapper>

4. Test

image-20230310113412445

Requirement 2: Query user information with user id 1 and user photo information (one-to-many)

1. Create UserPhotoInfoBO business package object

/**
 * @Project: mybatis-wx-demo
 * @Author: [email protected]
 * @Create: 2023/3/10 11:40
 * @Description:
 **/
@Data
public class UserPhotoInfoBO {
    
    
    private Integer id;
    private String userName;
    private Integer age;
    private LocalDateTime createTime;
    private List<UserPhoto> userPhotoList;
}

2. Write the interface

public interface UserMapper {
    
    
    UserAccountInfoBO selectUserAndAccountByUserId(@Param("id") Integer id);
    UserPhotoInfoBO selectUserAndPhotoByUserId(@Param("id") Integer id);
}

3. Write the xml configuration file

Use the collection tag to encapsulate the Bean collection, and the photos are multiple

<resultMap id="selectUserAndPhotoByUserIdMap" type="com.cxs.bo.UserPhotoInfoBO">
        <id property="id" column="id" jdbcType="INTEGER"/>
        <result property="userName" column="user_name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <collection property="userPhotoList" javaType="java.util.List" ofType="com.cxs.model.UserPhoto">
            <id property="id" column="photo_id" jdbcType="INTEGER"/>
            <result property="url" column="url" jdbcType="VARCHAR"/>
            <result property="userId" column="user_id" jdbcType="INTEGER"/>
        </collection>
    </resultMap>

    <select id="selectUserAndPhotoByUserId" resultMap="selectUserAndPhotoByUserIdMap" parameterType="java.lang.Integer">
        select u.*,
               up.id as photo_id,
               up.user_id,
               up.url
        from user u
        inner join user_photo up
        on u.id = up.user_id
        where u.id = #{id}
    </select>

4. Test

image-20230310131812457

Requirement 3: Query user information with user id 1 and user role information (many-to-many)

1. Create a UserRoleInfoBO business encapsulation object

/**
 * @Project: mybatis-wx-demo
 * @Author: [email protected]
 * @Create: 2023/3/10 13:19
 * @Description:
 **/
@Data
public class UserRoleInfoBO {
    
    
    private Integer id;
    private String userName;
    private Integer age;
    private LocalDateTime createTime;
    private List<Role> roleList;
}

2. Write the interface

/**
 * @Project: mybatis-wx-demo
 * @Author: [email protected]
 * @Create: 2023/2/28 10:41
 * @Description:
 **/
public interface UserMapper {
    
    

    UserAccountInfoBO selectUserAndAccountByUserId(@Param("id") Integer id);

    UserPhotoInfoBO selectUserAndPhotoByUserId(@Param("id") Integer id);

    UserRoleInfoBO selectUserAndRoleListByUserId(@Param("id") Integer id);
}

3. Write the xml configuration file

<resultMap id="selectUserAndRoleListByUserIdMap" type="com.cxs.bo.UserRoleInfoBO">
        <id property="id" column="id" jdbcType="INTEGER"/>
        <result property="userName" column="user_name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <collection property="roleList" javaType="java.util.List" ofType="com.cxs.model.Role">
            <id property="roleId" column="role_id" jdbcType="INTEGER"/>
            <result property="roleName" column="role_name" jdbcType="VARCHAR"/>
        </collection>
    </resultMap>

    <select id="selectUserAndRoleListByUserId" resultMap="selectUserAndRoleListByUserIdMap" parameterType="java.lang.Integer">
        select u.*, r.*
        from user u
        left join user_role ur on u.id = ur.u_id
        inner join role r on ur.r_id = r.role_id
        where u.id = #{id}
    </select>

4. Test

image-20230310132450172

epilogue

1. Three different relational mappings. That’s it. I don’t know if you have discovered that one-to-many and many-to-many are very similar, but the SQL statement is different.

2. For Mybatis related content, dynamic SQL, cache and SpringBoot will be arranged to integrate Mybatis in the future

3. It's not easy to make, let's go with one click and three consecutive times. Your support is my biggest motivation!

Guess you like

Origin blog.csdn.net/admin_2022/article/details/130719526