[MyBatis] Custom resultMap three mapping relationships

Table of contents

1. One-to-One mapping (One-to-One)

1.1 Table relationship

1.2 resultMap set custom mapping 

Two, one-to-many mapping (One-to-Many)

2.1 Create entities

2.2 Cascade processing of mapping relationship

2.3 Define SQL

2.4 OrderMapper interface

2.5 Write business logic layer

2.6 Junit test

3. Many-to-Many mapping (Many-to-Many)

3.1 Table relationship

3.2 Create entities

3.3 Handle the mapping relationship and define sql

3.4 HBookMapper interface

3.5 Write business logic layer

3.6 Junit test


1. One-to-One mapping (One-to-One)

1.1 Table relationship

         A one-to-one mapping is when one object has a one-to-one relationship with another object. For example, the relationship between a user (User) and an address (Address). Suppose we have the following table structure:

user table:

id (int)
name (varchar)
address_id (int)

address table:

id (int)
street (varchar)
city (varchar)

First, create User and Address entity classes:

User.java

public class User {
    private int id;
    private String name;
    private Address address;
    // getters and setters
}

Address.java

public class Address {
    private int id;
    private String street;
    private String city;
    // getters and setters
}

Next, create a resultMap for one-to-one mapping:

1.2 resultMap set custom mapping 

UserMapper.xml

<resultMap id="UserAddressResultMap" type="User">
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    //一对一关系使用association
    <association property="address" javaType="Address">
        <id property="id" column="address_id"/>
        <result property="street" column="street"/>
        <result property="city" column="city"/>
    </association>
</resultMap>

Attributes:

  • id: Indicates the unique identifier of the custom mapping
  • type: the type of entity class to be mapped to the queried data

sub-tab:

  • id: Set the mapping relationship of the primary key
  • result: Set the mapping relationship of common fields
  • association : Set up a many-to-one mapping relationship
  • collection: Set up a one-to-many mapping relationship

Subtag attributes:

  • property: Set the attribute name in the entity class in the mapping relationship
  • column: Set the field name in the table in the mapping relationship

Finally, write a query method to use this resultMap: 

UserMapper.xml

<select id="findUserWithAddress" resultMap="UserAddressResultMap">
    SELECT u.id, u.name, a.id as address_id, a.street, a.city
    FROM user u
    INNER JOIN address a ON u.address_id = a.id
    WHERE u.id = #{id}
</select>

        Finally, implement the interface findUserWithAddress method test. Through the above simple cases, I believe you already understand the custom relationship mapping. Often the data and tables in actual development are more complicated. For advanced usage, please see the following examples:

Two, one-to-many mapping (One-to-Many)

        A one-to-many mapping means that an object has a one-to-many relationship with many objects. For example, the relationship between an order (Oeder) and an order detail (OrderItem). Suppose we have the following table structure:

2.1 Create entities

 Use mybatis reverse engineering (generatorConfig.xml) to generate model layer code:

   创建 OrderVo It is a value object (Value Object), inheriting  Order the class and adding an extra property  orderItems. This class is used to pass data between the various layers of the application, especially between the presentation layer and the business logic layer. In this example, OrderVo the class is used to represent an order and its associated line items.

package com.ycxw.vo;

import com.ycxw.model.Order;
import com.ycxw.model.OrderItem;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-26 16:30
 */
@Data
public class OrderVo extends Order {
    private List<OrderItem> orderItems = new ArrayList<>();
}

2.2 Cascade processing of mapping relationship

    <resultMap id="OrderVoMap" type="com.ycxw.vo.OrderVo">
        <result column="order_id" property="orderId"></result>
        <result column="order_no" property="orderNo"></result>
        //多关系使用collection
        <collection property="orderItems" ofType="com.ycxw.model.OrderItem">
            <result column="order_item_id" property="orderItemId"></result>
            <result column="product_id" property="productId"></result>
            <result column="quantity" property="quantity"></result>
            <result column="oid" property="oid"></result>
        </collection>
    </resultMap>

2.3 Define SQL

    <select id="SelectByOid" resultMap="OrderVoMap" parameterType="java.lang.Integer">
        SELECT *
        FROM t_hibernate_order o,
             t_hibernate_order_item oi
        WHERE o.order_id = oi.oid
          AND o.order_id = #{oid}
    </select>

2.4 OrderMapper interface

package com.ycxw.mapper;

import com.ycxw.model.Order;
import com.ycxw.vo.OrderVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface OrderMapper {

    OrderVo SelectByOid(@Param("oid") Integer oid);
}

2.5 Write business logic layer

OrderItmeBiz interface
package com.ycxw.biz;

import com.ycxw.vo.OrderItemVo;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-26 21:48
 */
public interface OrderItmeBiz {
    OrderItemVo SelectByOitemId(Integer oiid);
}
OrderBizImpl interface implementation class
package com.ycxw.biz.impl;

import com.ycxw.biz.OrderBiz;
import com.ycxw.mapper.OrderMapper;
import com.ycxw.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-26 16:46
 */
@Service
public class OrderBizImpl implements OrderBiz {
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public OrderVo SelectByOid(Integer oid) {
        return orderMapper.SelectByOid(oid);
    }
}

2.6 Junit test

package com.ycxw.biz.impl;

import com.ycxw.biz.OrderBiz;
import com.ycxw.vo.OrderVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-26 16:48
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class OrderBizImplTest {
    @Autowired
    private OrderBiz orderBiz;


    @Test
    public void selectByOid() {
        OrderVo orderVo = orderBiz.SelectByOid(8);
        //获取订单
        System.out.println(orderVo);
        //获取订单项信息
        orderVo.getOrderItems().forEach(System.out::println);
    }

}

operation result:

3. Many-to-Many mapping (Many-to-Many)

3.1 Table relationship

        A many-to-many mapping is when multiple objects have a many-to-many relationship with multiple objects. The many-to-many relationship between tables is a little more complicated and requires an intermediate table to represent:

        The intermediate table has three fields, two of which are used as foreign keys to point to the primary key of each party, so the many-to-many relationship is represented through the intermediate table, and the one-to-many relationship can be expressed by combining one table with another intermediate table.

 

 For example: Find the associated attribute category according to the book id:

3.2 Create entities

Use mybatis reverse engineering (generatorConfig.xml) to generate model layer code:

 

Create HBookVo value object (Value Object)

package com.ycxw.vo;

import com.ycxw.model.BookCategory;
import com.ycxw.model.HBook;
import lombok.Data;

import java.util.List;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-27 21:03
 */
@Data
public class HBookVo extends HBook {
    private List<BookCategory> bookc = new ArrayList<>();
}

3.3 Handle the mapping relationship and define sql

  <resultMap id="HBookVoMap" type="com.ycxw.vo.HBookVo" >
    <result column="book_id" property="bookId"></result>
    <result column="book_name" property="bookName"></result>
    <result column="price" property="price"></result>
    <collection property="bookc" ofType="com.ycxw.model.Category">
      <result column="category_id" property="categoryId"></result>
      <result column="category_name" property="categoryName"></result>
    </collection>
  </resultMap>

  <!--根据书籍的id查询书籍的信息及所属属性-->
  <select id="selectByBookId" resultMap="HBookVoMap" parameterType="java.lang.Integer">
    SELECT
      *
    FROM
      t_hibernate_book b,
      t_hibernate_category c,
      t_hibernate_book_category bc
    WHERE
      b.book_id = bc.bid
      AND c.category_id = bc.bcid
      AND b.book_id = #{bid}
  </select>

3.4 HBookMapper interface

HBookVo selectByBookId(@Param("bid") Integer bid);

3.5 Write business logic layer

HBookBiz interface
package com.ycxw.biz;

import com.ycxw.vo.HBookVo;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-29 12:47
 */
public interface HBookBiz {
    HBookVo selectByBookId(Integer bid);
}
HBookBizImpl interface implementation class
package com.ycxw.biz.impl;

import com.ycxw.biz.HBookBiz;
import com.ycxw.mapper.HBookMapper;
import com.ycxw.vo.HBookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-29 12:48
 */
@Service
public class HBookBizImpl implements HBookBiz {
    @Autowired
    private HBookMapper hBookMapper;
    @Override
    public HBookVo selectByBookId(Integer bid) {
        return hBookMapper.selectByBookId(bid);
    }
}

3.6 Junit test

package com.ycxw.biz.impl;

import com.ycxw.biz.HBookBiz;
import com.ycxw.vo.HBookVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author 云村小威
 * @site blog.csdn.net/Justw320
 * @create 2023-08-26 16:48
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class OrderBizImplTest {
    @Autowired
    private HBookBiz hBookBiz;


    @Test
    public void selectByBookId(){
        HBookVo hBookVo = hBookBiz.selectByBookId(22);
        //数据所有信息
        System.out.println(hBookVo);
        //书籍有关的类别
        System.out.println(hBookVo.getBookc());
    }
}

 And vice versa, such as: find book information based on category id

 <resultMap id="CategotyVoMap" type="com.ycxw.vo.CategoryVo">
    <result column="category_id" property="categoryId"></result>
    <result column="category_name" property="categoryName"></result>
    <collection property="books" ofType="com.ycxw.model.HBook">
      <result column="book_id" property="bookId"></result>
      <result column="book_name" property="bookName"></result>
      <result column="price" property="price"></result>
    </collection>
  </resultMap>

  <select id="selectCategoryId" resultMap="CategotyVoMap" parameterType="java.lang.Integer">
    SELECT
      *
    FROM
      t_hibernate_book b,
      t_hibernate_category c,
      t_hibernate_book_category bc
    WHERE
      b.book_id = bc.bid
      AND c.category_id = bc.bcid
      AND c.category_id = #{cid}
  </select>

Test run:

Guess you like

Origin blog.csdn.net/Justw320/article/details/132512497