[Mybatis from entry to actual combat tutorial] Chapter 5 Detailed Explanation of Mybatis Association Query

5. Mybatis associated query

5.1 Data model analysis

5.1.1 Table function introduction

  • User Table: Record the basic information of users.

  • Order table: Records the orders created by users (orders for purchasing goods).

  • Order details table: Record the details of the order, that is, the information of the purchased goods.

  • Product table: Record the basic information of the product.

5.1.2 Business relationship between tables

User table and order table:

  • User table ---> order table: a user can create multiple orders, one-to-many relationship;

  • Order table ---> User table: An order is created by only one user, one-to-one relationship;

Order Form and Order Details Form:

  • Order table ---> order details table: An order can contain multiple order details, because one order can purchase multiple items, and the purchase information of each item is recorded in the order details table, a one-to-many relationship;

  • Order details table ---> Order table: An order detail can only be included in one order, one-to-one relationship;

Order details table and product table:

  • Order details table ---> Product table: An order detail corresponds to only one product information, a one-to-one relationship;

  • Product table ---> order details table: a product can be included in multiple order details, one-to-many relationship;

Order table and product table:

  • Order table <---> Commodity table: An order contains multiple commodities, and one commodity can be added to multiple orders. The relationship between the two is established through the order details table, a many-to-many relationship;

Notice:

  • If two tables have primary and foreign key associations, their business relationship is one-to-one/one-to-many, or bidirectional one-to-one (such as user table and user detail table).

  • If two tables are bidirectional one-to-many relationships, then they are many-to-many relationships, and there must be a relationship description table as an intermediate table.

5.1.3 Table structure

user table:

CREATE TABLE `users`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(20),
  `password` varchar(50),
  `realname` varchar(20)
);

INSERT INTO `users` VALUES (1, 'admin', '123456', '管理员');
INSERT INTO `users` VALUES (2, 'tom', '123', '汤姆');
INSERT INTO `users` VALUES (3, 'jerry', '456', '杰瑞');
INSERT INTO `users` VALUES (4, 'zhangsan', '111', '张三');
INSERT INTO `users` VALUES (5, 'lisi', '222', '李四');

Order form:

CREATE TABLE `orders`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `order_number` varchar(30),
  `total_price` double,
  `status` varchar(5),
  `user_id` int(11)
);
​
INSERT INTO `orders` VALUES (1, '201812290838001', 2535, '已评价', 2);
INSERT INTO `orders` VALUES (2, '201812290838002', 4704.6, '已签收', 2);
INSERT INTO `orders` VALUES (3, '201812290838003', 3620, '已支付', 2);
INSERT INTO `orders` VALUES (4, '201812290840001', 600, '已发货', 3);
INSERT INTO `orders` VALUES (5, '201812290840002', 280, '未支付', 3);

Order details table:

CREATE TABLE `orders_detail`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `amount` int(11),
  `goods_id` int(11),
  `orders_id` int(11)
);
​
INSERT INTO `orders_detail` VALUES (1, 1, 1, 1);
INSERT INTO `orders_detail` VALUES (2, 3, 8, 1);
INSERT INTO `orders_detail` VALUES (3, 1, 2, 2);
INSERT INTO `orders_detail` VALUES (4, 2, 7, 2);
INSERT INTO `orders_detail` VALUES (5, 1, 3, 3);
INSERT INTO `orders_detail` VALUES (6, 6, 6, 3);
INSERT INTO `orders_detail` VALUES (7, 2, 4, 4);
INSERT INTO `orders_detail` VALUES (8, 1, 5, 5);

Commodity list:

CREATE TABLE `goods`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `goods_name` varchar(50),
  `description` varchar(500),
  `price` double
);
​
INSERT INTO `goods` VALUES (1, '手机', '手机', 2499);
INSERT INTO `goods` VALUES (2, '笔记本电脑', '笔记本电脑', 4699);
INSERT INTO `goods` VALUES (3, 'IPAD', 'IPAD', 3599);
INSERT INTO `goods` VALUES (4, '运动鞋', '运动鞋', 300);
INSERT INTO `goods` VALUES (5, '外套', '外套', 280);
INSERT INTO `goods` VALUES (6, '可乐', '可乐', 3.5);
INSERT INTO `goods` VALUES (7, '辣条', '辣条', 2.8);
INSERT INTO `goods` VALUES (8, '水杯', '水杯', 12);

5.2 One-to-one query

5.2.1 Requirements

    Query order information. The association is as follows:    
        1. Association query related user information.

5.2.2 Realized by resultType

Entity class:

    The entity class Orders cannot map all the fields, and a newly created entity class is required to create an entity class that includes more query fields. OrdersQuery contains the attributes that Orders and Users need to query.

package com.newcapec.vo;

/**
 * OrdersQuery值对象,不是entity/po,因为它和数据库中表的字段不是对应关系
 */
public class OrdersQuery {

    //订单属性
    private Integer id;
    private String orderNumber;
    private Double totalPrice;
    private String status;
    private Integer userId;
    //用户属性
    private String username;
    private String password;
    private String realname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public Double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    @Override
    public String toString() {
        return "OrdersQuery{" +
            "id=" + id +
            ", orderNumber='" + orderNumber + '\'' +
            ", totalPrice=" + totalPrice +
            ", status='" + status + '\'' +
            ", userId=" + userId +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            ", realname='" + realname + '\'' +
            '}';
    }
}

mapper interface:

package com.newcapec.mapper;

import com.newcapec.vo.OrdersQuery;

import java.util.List;

public interface OrdersMapper {

    List<OrdersQuery> selectUseResultType();
}

mapper file:

<?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.newcapec.mapper.OrdersMapper">

    <select id="selectUseResultType" resultType="com.newcapec.vo.OrdersQuery">
        select a.id,a.order_number,a.total_price,a.status,a.user_id,b.username,b.password,b.realname
        from orders a, users b where a.user_id=b.id
    </select>
</mapper>

test:

public class QueryTest {

    @Test
    public void testOneToOneResultType() {
        SqlSession sqlSession = MybatisUtil.getSession();
        OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
        List<OrdersQuery> list = ordersMapper.selectUseResultType();
        for (OrdersQuery ordersQuery : list) {
            System.out.println(ordersQuery);
        }
        sqlSession.close();
    }
}

5.2.3 Realized by resultMap

  • 5.2.3.1 Entity class

User class:

package com.newcapec.entity;

public class Users {

    private Integer id;
    private String username;
    private String password;
    private String realname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    @Override
    public String toString() {
        return "Users{" +
            "id=" + id +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            ", realname='" + realname + '\'' +
            '}';
    }
}

Order class:

    Add the Users attribute to the Orders class, and the Users attribute is used to store user information for associated queries.

    Because the order association query user is a one-to-one relationship, a single Users object is used here to store the user information of the association query.

package com.newcapec.entity;

public class Orders {

    private Integer id;
    private String orderNumber;
    private Double totalPrice;
    private String status;
    private Integer userId;
    /**
     * 一对一关系属性
     */
    private Users users;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public Double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", orderNumber='" + orderNumber + '\'' +
                ", totalPrice=" + totalPrice +
                ", status='" + status + '\'' +
                ", userId=" + userId +
                ", users=" + users +
                '}';
    }
}
  • 5.2.3.2 mapper interface
List<Orders> selectUseResultMap();
  • 5.2.3.3 mapper file

    association tag: One-to-one relationship mapping description.
        property: the name of the relationship property
        javaType: the type of the relationship property

<resultMap id="selectResultMap" type="com.newcapec.entity.Orders">
    <id column="id" property="id"/>
    <result column="order_number" property="orderNumber"/>
    <result column="total_price" property="totalPrice"/>
    <result column="status" property="status"/>
    <result column="user_id" property="userId"/>
    <association property="users" javaType="com.newcapec.entity.Users">
        <id column="user_id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="realname" property="realname"/>
    </association>
</resultMap>
<select id="selectUseResultMap" resultMap="selectResultMap">
    select a.id,a.order_number,a.total_price,a.status,a.user_id,b.username,b.password,b.realname
    from orders a, users b where a.user_id=b.id
</select>
  • 5.2.3.4 Testing
@Test
public void testOneToOneResultMap() {
    SqlSession sqlSession = MybatisUtil.getSession();
    OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
    List<Orders> list = ordersMapper.selectUseResultMap();
    for (Orders orders : list) {
        System.out.println(orders);
    }
    sqlSession.close();
}

5.2.4 resultType and resultMap realize one-to-one query summary

  • resultType: It is relatively simple to use resultType. If the entity class does not include the queried column name, you need to add the attribute corresponding to the column name to complete the mapping. If the query result has no special requirements, it is recommended to use resultType.

  • resultMap: You need to define resultMap separately, which is a bit troublesome to implement. If you have special requirements for query results, you can use resultMap to map the associated query to the attributes of the entity class.

  • resultMap can implement lazy loading, but resultType cannot implement lazy loading.

5.3 One-to-many query

5.3.1 Requirements

    Query order information. The association is as follows:
        1. Associated query of its related user information
        2. Associated query of its related order details.

5.3.2 Entity classes

Order details class:

public class OrdersDetail {
    
    private Integer id;
    private Integer amount;
    private Integer ordersId;
    private Integer goodsId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }

    public Integer getOrdersId() {
        return ordersId;
    }

    public void setOrdersId(Integer ordersId) {
        this.ordersId = ordersId;
    }

    public Integer getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    @Override
    public String toString() {
        return "OrdersDetail{" +
                "id=" + id +
                ", amount=" + amount +
                ", ordersId=" + ordersId +
                ", goodsId=" + goodsId +
                '}';
    }
}

Order class:

    Add the List<OrdersDetail> detailList attribute to the Order class, and the details attribute is used to store the order details of the associated query.

    Because the order details of the order association query is a one-to-many relationship, the collection object is used here to store the order details information of the association query.

public class Orders {

    private Integer id;
    private String orderNumber;
    private Double totalPrice;
    private String status;
    private Integer userId;
    /**
     * 一对一关系属性
     */
    private Users users;
    /**
     * 一对多关系属性
     */
    private List<OrdersDetail> detailList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public Double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    public List<OrdersDetail> getDetailList() {
        return detailList;
    }

    public void setDetailList(List<OrdersDetail> detailList) {
        this.detailList = detailList;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", orderNumber='" + orderNumber + '\'' +
                ", totalPrice=" + totalPrice +
                ", status='" + status + '\'' +
                ", userId=" + userId +
                ", users=" + users +
                ", detailList=" + detailList +
                '}';
    }
}

5.3.3 mapper interface

List<Orders> selectOrdersAndDetail();

5.3.4 mapper file

    collection tag: One-to-many relationship mapping description.
        property: the name of the relationship property
        ofType: the relationship property is a List collection, the type of elements stored in the collection

<resultMap id="detailResultMap" type="com.newcapec.entity.Orders">
    <id column="id" property="id"/>
    <result column="order_number" property="orderNumber"/>
    <result column="total_price" property="totalPrice"/>
    <result column="status" property="status"/>
    <result column="user_id" property="userId"/>
    <association property="users" javaType="com.newcapec.entity.Users">
        <id column="user_id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="realname" property="realname"/>
    </association>
    <collection property="detailList" ofType="com.newcapec.entity.OrdersDetail">
        <id column="detail_id" property="id"/>
        <result column="amount" property="amount"/>
        <result column="goods_id" property="goodsId"/>
        <result column="id" property="ordersId"/>
    </collection>
</resultMap>
<select id="selectOrdersAndDetail" resultMap="detailResultMap">
    select a.id,a.order_number,a.total_price,a.status,a.user_id,b.username,b.password,b.realname,
    c.id detail_id,c.amount,c.goods_id
    from orders a
    join users b on a.user_id=b.id
    join orders_detail c on a.id=c.orders_id
</select>

5.3.5 Testing

@Test
public void testOneToMany() {
    SqlSession sqlSession = MybatisUtil.getSession();
    OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
    List<Orders> list = ordersMapper.selectOrdersAndDetail();
    for (Orders orders : list) {
        System.out.println(orders);
    }
    sqlSession.close();
}

5.4 Many-to-many queries

5.4.1 Orders and Commodities

  • 5.4.1.1 Requirements

    Query order information. The association is as follows:
        1. Associated query of its relevant user information
        2. Associated query of its related order details
        3. Associated query of product information in the order details

  • 5.4.1.2 Entity class

    Change the goods_id attribute of the Integer type in the OrderDetail class to the Goods type attribute, and the goods attribute is used to store the product information of the associated query.

    Orders and order details have a one-to-many relationship. Order details and products have a one-to-one relationship. Conversely, products and order details have a one-to-many relationship. Order details and orders have a one-to-one relationship. Therefore, orders and products are many-to-many relation.

Commodity category:

public class Goods {

    private Integer id;
    private String goodsName;
    private String description;
    private Double price;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "id=" + id +
                ", goodsName='" + goodsName + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                '}';
    }
}

Order details class:

public class OrdersDetail {

    private Integer id;
    private Integer amount;
    private Integer ordersId;
    private Integer goodsId;
    /**
     * 一对一关系
     */
    private Goods goods;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }

    public Integer getOrdersId() {
        return ordersId;
    }

    public void setOrdersId(Integer ordersId) {
        this.ordersId = ordersId;
    }

    public Integer getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    public Goods getGoods() {
        return goods;
    }

    public void setGoods(Goods goods) {
        this.goods = goods;
    }

    @Override
    public String toString() {
        return "OrdersDetail{" +
                "id=" + id +
                ", amount=" + amount +
                ", ordersId=" + ordersId +
                ", goodsId=" + goodsId +
                ", goods=" + goods +
                '}';
    }
}
  • 5.4.1.3 mapper interface
List<Orders> selectOrdersAndGoods();
  • 5.4.1.4 mapper file
<resultMap id="goodsResultMap" type="com.newcapec.entity.Orders">
    <id column="id" property="id"/>
    <result column="order_number" property="orderNumber"/>
    <result column="total_price" property="totalPrice"/>
    <result column="status" property="status"/>
    <result column="user_id" property="userId"/>
    <association property="users" javaType="com.newcapec.entity.Users">
        <id column="user_id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="realname" property="realname"/>
    </association>
    <collection property="detailList" ofType="com.newcapec.entity.OrdersDetail">
        <id column="detail_id" property="id"/>
        <result column="amount" property="amount"/>
        <result column="goods_id" property="goodsId"/>
        <result column="id" property="ordersId"/>
        <association property="goods" javaType="com.newcapec.entity.Goods">
            <id column="goods_id" property="id"/>
            <result column="goods_name" property="goodsName"/>
            <result column="description" property="description"/>
            <result column="price" property="price"/>
        </association>
    </collection>
</resultMap>
<select id="selectOrdersAndGoods" resultMap="goodsResultMap">
    select a.id,a.order_number,a.total_price,a.status,a.user_id,b.username,b.password,b.realname,
    c.id detail_id,c.amount,c.goods_id,d.goods_name,d.description,d.price
    from orders a
    join users b on a.user_id=b.id
    join orders_detail c on a.id=c.orders_id
    join goods d on c.goods_id=d.id
</select>
  • 5.4.1.5 Testing
@Test
public void testManyToMany1() {
    SqlSession sqlSession = MybatisUtil.getSession();
    OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
    List<Orders> list = ordersMapper.selectOrdersAndGoods();
    for (Orders orders : list) {
        System.out.println(orders);
    }
    sqlSession.close();
}

5.4.2 Many-to-many relationship between students and courses

  • 5.4.2.1 Requirements

    Query student information, and associate query the corresponding course information of students.

  • 5.4.2.2 Table structure
CREATE TABLE `course`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `cname` varchar(20)
);

INSERT INTO `course` VALUES (1, '大学语文');
INSERT INTO `course` VALUES (2, '大学英语');
INSERT INTO `course` VALUES (3, '高等数学');
INSERT INTO `course` VALUES (4, 'JAVA语言');
INSERT INTO `course` VALUES (5, '网络维护');
INSERT INTO `course` VALUES (6, '通信原理');

CREATE TABLE `student`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(20),
  `gender` varchar(20),
  `major` varchar(20)
);

INSERT INTO `student` VALUES (1, '小明', '男', '软件工程');
INSERT INTO `student` VALUES (2, '小红', '女', '网络工程');
INSERT INTO `student` VALUES (3, '小丽', '女', '物联网');

CREATE TABLE `student_course`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `student_id` int(11),
  `course_id` int(11)
);

INSERT INTO `student_course` VALUES (1, 1, 1);
INSERT INTO `student_course` VALUES (2, 1, 3);
INSERT INTO `student_course` VALUES (3, 1, 4);
INSERT INTO `student_course` VALUES (4, 2, 1);
INSERT INTO `student_course` VALUES (5, 2, 2);
INSERT INTO `student_course` VALUES (6, 2, 5);
INSERT INTO `student_course` VALUES (7, 3, 2);
INSERT INTO `student_course` VALUES (8, 3, 3);
INSERT INTO `student_course` VALUES (9, 3, 6);
  • 5.4.2.3 Entity class

Course category:

public class Course {

    private Integer id;
    private String cname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", cname='" + cname + '\'' +
                '}';
    }
}

Student class:

public class Student {
    private Integer id;
    private String name;
    private String gender;
    private String major;

    /**
     * 一对多
     */
    private List<Course> courseList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public List<Course> getCourseList() {
        return courseList;
    }

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", major='" + major + '\'' +
                ", courseList=" + courseList +
                '}';
    }
}
  • 5.4.2.4 mapper interface
public interface StudentMapper {
    
    List<Student> select();
}
  • 5.4.2.5 mapper file
<?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.newcapec.mapper.StudentMapper">

    <resultMap id="selectResultMap" type="com.newcapec.entity.Student">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <result column="major" property="major"/>
        <collection property="courseList" ofType="com.newcapec.entity.Course">
            <id column="course_id" property="id"/>
            <result column="cname" property="cname"/>
        </collection>
    </resultMap>
    <select id="select" resultMap="selectResultMap">
        select a.id,a.name,a.gender,a.major,b.course_id,c.cname
        from student a
                 join student_course b on a.id=b.student_id
                 join course c ON b.course_id=c.id
    </select>
</mapper>
  • 5.4.2.6 Testing
@Test
public void testManyToMany2() {
    SqlSession sqlSession = MybatisUtil.getSession();
    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
    List<Student> list = studentMapper.select();
    for (Student student : list) {
        System.out.println(student);
    }
    sqlSession.close();
}

5.5 Summary of associated queries

5.5.1 resultType

    Function: Map query results to entity class objects according to the consistency of SQL column names and entity class attribute names.
    
    Occasion: It is common to display some detailed records. For example, when a user purchases product details and displays all related query information on the page, you can directly use resultType to map each record to an entity class, and traverse the list on the front-end page (the list is Entity class) can be.

5.5.2 resultMap

    Use association and collection to complete one-to-one and one-to-many advanced mapping (there are special mapping requirements for the result).

association

    Role: Map the associated query information to an entity class object.

    Occasion: In order to facilitate the query of related information, association can be used to map the related information to an attribute of the current object, such as querying order and related user information.

collection

    Function: Map the associated query information to a list collection.

    Occasion: In order to facilitate the query and traversal of related information, you can use collection to map related information to the list collection. For example: to query the user authority scope module and the menu under the module, you can use collection to map the module to the module list, and map the menu list to the module In the menu list attribute of the object, the purpose of this operation is also to facilitate the traversal query of the query result set. If resultType is used, the query result cannot be mapped to the list collection.

Inheritance of resultMap

     The resultMap tag can inherit an existing or public resultMap through the extends attribute, avoiding repeated configuration and reducing the amount of configuration.

Examples are as follows:

<!-- 父resultMap标签-->
<resultMap id="baseResultMap" type="com.newcapec.entity.Orders">
    <id column="id" property="id"/>
    <result column="order_number" property="orderNumber"/>
    <result column="total_price" property="totalPrice"/>
    <result column="status" property="status"/>
    <result column="user_id" property="userId"/>
</resultMap>
<!-- 继承父resultMap标签中的配置,避免重复配置 -->
<resultMap id="subResultMap" type="com.newcapec.entity.Orders" extends="baseResultMap">
    <association property="users" javaType="com.newcapec.entity.Users">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="realname" property="realname"/>
    </association>
</resultMap>

Guess you like

Origin blog.csdn.net/ligonglanyuan/article/details/124396983