Mybatis mapping relationship configuration

One, one to one

One-to-one mapping means that one object has a one-to-one relationship with another object

1.1  Table relationship

         One-to-one mapping means that one object has a one-to-one relationship with another object. For example, the relationship between a user and an 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 the User and Address entity classes:

User.class

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

Address.class

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 sets 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: a unique identifier representing custom mapping
type: the type of entity class to which the queried data is to be mapped Sub-
tags:

id: Set the primary key mapping relationship
result: Set the common field mapping relationship
association: Set the many-to-one mapping relationship
collection: Set the one-to-many mapping relationship
Sub-tag attributes:

property: Set the property 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 to test. Through the above simple case, I believe you already understand the custom relationship mapping. In actual development, data and tables are often much more complicated. For advanced usage, please see the following examples:
 

 

2. One-to-Many Mapping (One-to-Many)

        One-to-many mapping means that one object has a one-to-many relationship with multiple 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:

package com.xzs.model;

import lombok.ToString;

@ToString
public class order {
    private Integer orderId;

    private String orderNo;

    public order(Integer orderId, String orderNo) {
        this.orderId = orderId;
        this.orderNo = orderNo;
    }

    public order() {
        super();
    }

    public Integer getOrderId() {
        return orderId;
    }

    public void setOrderId(Integer orderId) {
        this.orderId = orderId;
    }

    public String getOrderNo() {
        return orderNo;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }
}
package com.xzs.model;

import lombok.ToString;

@ToString
public class orderItem {
    private Integer orderItemId;

    private Integer productId;

    private Integer quantity;

    private Integer oid;

    public orderItem(Integer orderItemId, Integer productId, Integer quantity, Integer oid) {
        this.orderItemId = orderItemId;
        this.productId = productId;
        this.quantity = quantity;
        this.oid = oid;
    }

    public orderItem() {
        super();
    }

    public Integer getOrderItemId() {
        return orderItemId;
    }

    public void setOrderItemId(Integer orderItemId) {
        this.orderItemId = orderItemId;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Integer getOid() {
        return oid;
    }

    public void setOid(Integer oid) {
        this.oid = oid;
    }
}

创建 OrderVo It is a Value Object that inherits  Order the class and adds an extra property  orderItems. This class is used to pass data between various layers of the application, especially between the presentation layer and the business logic layer. In this example, OrderVo the class represents an order and its associated line items.

package com.xzs.vo;
 
import com.xzs.model.Order;
import com.xzs.model.OrderItem;
import lombok.Data;
 
import java.util.ArrayList;
import java.util.List;
 

@Data
public class OrderVo extends Order {
    private List<OrderItem> orderItems = new ArrayList<>();
}

2.2 Processing mapping relationships in cascade mode

    <resultMap id="OrderVoMap" type="com.xzs.vo.OrderVo">
        <result column="order_id" property="orderId"></result>
        <result column="order_no" property="orderNo"></result>
        //多关系使用collection
        <collection property="orderItems" ofType="com.xzs.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.xzs.mapper;
 
import com.xzs.model.Order;
import com.xzs.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 Writing the business logic layer

OrderItmeBiz interface
package com.xzs.biz;
 
import com.xzs.vo.OrderItemVo;
 

public interface OrderItmeBiz {
    OrderItemVo SelectByOitemId(Integer oid);
}
OrderBizImpl interface implementation class
package com.xzs.biz.impl;
 
import com.xzs.biz.OrderBiz;
import com.xzs.mapper.OrderMapper;
import com.xzs.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 

@Service
public class OrderBizImpl implements OrderBiz {
    @Autowired
    private OrderMapper orderMapper;
 
    @Override
    public OrderVo SelectByOid(Integer oid) {
        return orderMapper.SelectByOid(oid);
    }
}

3. Many-to-Many Mapping (Many-to-Many)

3.1 Table relationship
        many-to-many mapping refers to a many-to-many relationship between multiple objects and multiple objects. The many-to-many relationship between tables is slightly more complicated and requires an intermediate table to represent it:

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

 

 

For example: Find the associated attribute category based on the book ID:

3.2 Create entities

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

package com.xzs.model;

import lombok.ToString;

@ToString
public class HCategory {
    private Integer categoryId;

    private String categoryName;

    public HCategory(Integer categoryId, String categoryName) {
        this.categoryId = categoryId;
        this.categoryName = categoryName;
    }

    public HCategory() {
        super();
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
}

 

package com.xzs.model;

import lombok.ToString;

@ToString
public class HBookCategory {
    private Integer bcid;

    private Integer bid;

    private Integer cid;

    public HBookCategory(Integer bcid, Integer bid, Integer cid) {
        this.bcid = bcid;
        this.bid = bid;
        this.cid = cid;
    }

    public HBookCategory() {
        super();
    }

    public Integer getBcid() {
        return bcid;
    }

    public void setBcid(Integer bcid) {
        this.bcid = bcid;
    }

    public Integer getBid() {
        return bid;
    }

    public void setBid(Integer bid) {
        this.bid = bid;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }
}

 

package com.xzs.model;

import lombok.ToString;

@ToString
public class HBook {
    private Integer bookId;

    private String bookName;

    private Float price;

    public HBook(Integer bookId, String bookName, Float price) {
        this.bookId = bookId;
        this.bookName = bookName;
        this.price = price;
    }

    public HBook() {
        super();
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public Float getPrice() {
        return price;
    }

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

Create HBookVo value object (Value Object)

package com.xzs.vo;
 
import com.xzs.model.BookCategory;
import com.xzs.model.HBook;
import lombok.Data;
 
import java.util.List;
 

@Data
public class HBookVo extends HBook {
    private List<BookCategory> bookc = new ArrayList<>();
}

3.3 Process mapping relationships and define sql

  <resultMap id="HBookVoMap" type="com.xzs.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.xzs.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 Writing the business logic layer

HBookBiz interface
package com.xzs.biz;
 
import com.xzs.vo.HBookVo;
 

public interface HBookBiz {
    HBookVo selectByBookId(Integer bid);
}
HBookBizImpl interface implementation class
package com.xzs.biz.impl;
 
import com.xzs.biz.HBookBiz;
import com.xzs.mapper.HBookMapper;
import com.xzs.vo.HBookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class HBookBizImpl implements HBookBiz {
    @Autowired
    private HBookMapper hBookMapper;
    @Override
    public HBookVo selectByBookId(Integer bid) {
        return hBookMapper.selectByBookId(bid);
    }
}

Guess you like

Origin blog.csdn.net/weixin_72997875/article/details/132663221