mybatis之关联关系映射

文章目录

一对多关联关系映射(以订单和订单项为例)

首先先用逆向生成工具生成t_hibernate_order、t_hibernate_order_item
这两张表对应的model与mapper
一对多标签:

	<association></association>

生成之后直接上代码:

mapper包:

OrderItemMapper:

package com.yj.mapper;

import com.yj.model.OrderItem;
import com.yj.vo.OrderItemVo;
import org.apache.ibatis.annotations.Param;

import org.springframework.stereotype.Repository;

@Repository
public interface OrderItemMapper {
    int deleteByPrimaryKey(Integer orderItemId);

    int insert(OrderItem record);

    int insertSelective(OrderItem record);

    OrderItem selectByPrimaryKey(Integer orderItemId);

    int updateByPrimaryKeySelective(OrderItem record);

    int updateByPrimaryKey(OrderItem record);

    OrderItemVo selectByOrderItemId(@Param("orderItemId") Integer orderItemId);
}

OrderItemMapper.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.yj.mapper.OrderItemMapper" >
  <resultMap id="BaseResultMap" type="com.yj.model.OrderItem" >
    <constructor >
      <idArg column="order_item_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="product_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="quantity" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="oid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    </constructor>
  </resultMap>

<!--此处需要注意。一个id对应一个实体类的列段-->
  <resultMap id="OrderItemVoMap" type="com.yj.vo.OrderItemVo" >
    <result property="orderItemId" column="order_item_id"></result>
    <result property="productId" column="product_id"></result>
    <result property="quantity" column="quantity"></result>
    <result property="oid" column="oid"></result>
    <association property="order" javaType="com.yj.model.Order">
      <result property="orderId" column="order_id"></result>
      <result property="orderNo" column="order_no"></result>
    </association>
  </resultMap>


  <sql id="Base_Column_List" >
    order_item_id, product_id, quantity, oid
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_hibernate_order_item
    where order_item_id = #{orderItemId,jdbcType=INTEGER}
  </select>
  <select id="selectByOrderItemId" resultMap="OrderItemVoMap" parameterType="java.lang.Integer">
    select * from t_hibernate_order o,t_hibernate_order_item oi
    where o.order_id = oi.oid
    and oi.order_item_id = #{orderItemId}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_hibernate_order_item
    where order_item_id = #{orderItemId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.yj.model.OrderItem" >
    insert into t_hibernate_order_item (order_item_id, product_id, quantity, 
      oid)
    values (#{orderItemId,jdbcType=INTEGER}, #{productId,jdbcType=INTEGER}, #{quantity,jdbcType=INTEGER}, 
      #{oid,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.yj.model.OrderItem" >
    insert into t_hibernate_order_item
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="orderItemId != null" >
        order_item_id,
      </if>
      <if test="productId != null" >
        product_id,
      </if>
      <if test="quantity != null" >
        quantity,
      </if>
      <if test="oid != null" >
        oid,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="orderItemId != null" >
        #{orderItemId,jdbcType=INTEGER},
      </if>
      <if test="productId != null" >
        #{productId,jdbcType=INTEGER},
      </if>
      <if test="quantity != null" >
        #{quantity,jdbcType=INTEGER},
      </if>
      <if test="oid != null" >
        #{oid,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.yj.model.OrderItem" >
    update t_hibernate_order_item
    <set >
      <if test="productId != null" >
        product_id = #{productId,jdbcType=INTEGER},
      </if>
      <if test="quantity != null" >
        quantity = #{quantity,jdbcType=INTEGER},
      </if>
      <if test="oid != null" >
        oid = #{oid,jdbcType=INTEGER},
      </if>
    </set>
    where order_item_id = #{orderItemId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.yj.model.OrderItem" >
    update t_hibernate_order_item
    set product_id = #{productId,jdbcType=INTEGER},
      quantity = #{quantity,jdbcType=INTEGER},
      oid = #{oid,jdbcType=INTEGER}
    where order_item_id = #{orderItemId,jdbcType=INTEGER}
  </update>
</mapper>

OrderMapper:

package com.yj.mapper;

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

@Repository
public interface OrderMapper {
    int deleteByPrimaryKey(Integer orderId);

    int insert(Order record);

    int insertSelective(Order record);

    Order selectByPrimaryKey(Integer orderId);

    int updateByPrimaryKeySelective(Order record);

    int updateByPrimaryKey(Order record);

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

OrderMapper.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.yj.mapper.OrderMapper" >
  <resultMap id="BaseResultMap" type="com.yj.model.Order" >
    <constructor >
      <idArg column="order_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="order_no" jdbcType="VARCHAR" javaType="java.lang.String" />
    </constructor>
  </resultMap>

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

  <sql id="Base_Column_List" >
    order_id, order_no
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_hibernate_order
    where order_id = #{orderId,jdbcType=INTEGER}
  </select>
  <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>


  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_hibernate_order
    where order_id = #{orderId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.yj.model.Order" >
    insert into t_hibernate_order (order_id, order_no)
    values (#{orderId,jdbcType=INTEGER}, #{orderNo,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.yj.model.Order" >
    insert into t_hibernate_order
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="orderId != null" >
        order_id,
      </if>
      <if test="orderNo != null" >
        order_no,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="orderId != null" >
        #{orderId,jdbcType=INTEGER},
      </if>
      <if test="orderNo != null" >
        #{orderNo,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.yj.model.Order" >
    update t_hibernate_order
    <set >
      <if test="orderNo != null" >
        order_no = #{orderNo,jdbcType=VARCHAR},
      </if>
    </set>
    where order_id = #{orderId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.yj.model.Order" >
    update t_hibernate_order
    set order_no = #{orderNo,jdbcType=VARCHAR}
    where order_id = #{orderId,jdbcType=INTEGER}
  </update>
</mapper>

model包:

Order:

package com.yj.model;

public class Order {
    private Integer orderId;

    private String orderNo;

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

    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + orderId +
                ", 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;
    }
}

OrderItem:

package com.yj.model;


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;
    }

    @Override
    public String toString() {
        return "OrderItem{" +
                "orderItemId=" + orderItemId +
                ", productId=" + productId +
                ", quantity=" + quantity +
                ", 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;
    }
}

vo包:

OrderItemVo:

package com.yj.vo;

import com.yj.model.Order;
import com.yj.model.OrderItem;

/**
 * @author 仰望天空
 * @site
 * @company xxx公司
 * @create 2019-09-26 18:40
 */
public class OrderItemVo extends OrderItem {
    private Order order;

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }
}

OrderVo:

package com.yj.vo;

import com.yj.model.Order;
import com.yj.model.OrderItem;

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

/**
 * @author 仰望天空
 * @site
 * @company xxx公司
 * @create 2019-09-26 11:51
 */
public class OrderVo extends Order {
    private List<OrderItem> orderItems = new ArrayList<>();

    public List<OrderItem> getOrderItems() {
        return orderItems;
    }

    public void setOrderItems(List<OrderItem> orderItems) {
        this.orderItems = orderItems;
    }
}

Service包:

One2ManyService:

package com.yj.service;

import com.yj.vo.OrderItemVo;
import com.yj.vo.OrderVo;

/**
 * @author 仰望天空
 * @site
 * @company xxx公司
 * @create 2019-09-26 20:35
 */
public interface One2ManyService {
    OrderVo selectByOid(Integer oid);
    OrderItemVo selectByOrderItemId(Integer orderItemId);
}

Impl包:

One2ManyServiceImpl:

package com.yj.service.Impl;

import com.yj.mapper.OrderItemMapper;
import com.yj.mapper.OrderMapper;
import com.yj.service.One2ManyService;
import com.yj.vo.OrderItemVo;
import com.yj.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 仰望天空
 * @site
 * @company xxx公司
 * @create 2019-09-26 20:37
 */
@Service
public class One2ManyServiceImpl implements One2ManyService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Override
    public OrderVo selectByOid(Integer oid) {
        return orderMapper.selectByOid(oid);
    }

    @Override
    public OrderItemVo selectByOrderItemId(Integer orderItemId) {
        return orderItemMapper.selectByOrderItemId(orderItemId);
    }
}

测试类:

One2ManyServiceImplTest:

package com.yj.service.Impl;

import com.yj.SpringBaseTest;
import com.yj.model.OrderItem;
import com.yj.service.One2ManyService;
import com.yj.vo.OrderVo;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author 仰望天空
 * @site
 * @company xxx公司
 * @create 2019-09-26 20:41
 */
public class One2ManyServiceImplTest extends SpringBaseTest {
    @Autowired
    private One2ManyService one2ManyService;
    @Test
    public void selectByOid() {
        OrderVo orderVo = one2ManyService.selectByOid(2);
        System.out.println(orderVo);
        for (OrderItem orderItem : orderVo.getOrderItems()) {
            System.out.println(orderItem);
        }

    }

    @Test
    public void selectByOrderItemId() {
    }
}

结果图:
mybatis之关联关系映射

多对多关联关系映射(以书籍和书籍类别为例)

同样的操作,只不过换成了两个一对多的映射即可:
(建议在中间表操作,防止将来修改表之后要重新创建关联关系,而中间表只是两个id,即使修改了表,也不会影响关联关系)
这里直接将我操作的代码放上,同样的操作就不放代码了:

HbookCategoryMapper:

package com.yj.mapper;

import com.yj.model.HbookCategory;
import com.yj.vo.CategoryVo;
import com.yj.vo.HbookVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface HbookCategoryMapper {
    int deleteByPrimaryKey(Integer bcid);

    int insert(HbookCategory record);

    int insertSelective(HbookCategory record);

    HbookCategory selectByPrimaryKey(Integer bcid);

    int updateByPrimaryKeySelective(HbookCategory record);

    int updateByPrimaryKey(HbookCategory record);

    HbookVo queryByBid(@Param("bid") Integer bid);

    CategoryVo queryByCid(@Param("cid") Integer cid);
}

HbookCategoryMapper.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.yj.mapper.HbookCategoryMapper" >
  <resultMap id="BaseResultMap" type="com.yj.model.HbookCategory" >
    <constructor >
      <idArg column="bcid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    </constructor>
  </resultMap>

  <resultMap id="HbookVoMap" type="com.yj.vo.HbookVo" >
    <result property="bookId" column="book_id"></result>
    <result property="bookName" column="book_name"></result>
    <result property="price" column="price"></result>
    <collection property="categories" ofType="com.yj.model.Category">
      <result property="categoryId" column="category_id"></result>
      <result property="categoryName" column="category_name"></result>
    </collection>
  </resultMap>

  <resultMap id="CategoryVoMap" type="com.yj.vo.CategoryVo" >
    <result property="categoryId" column="category_id"></result>
    <result property="categoryName" column="category_name"></result>
    <collection property="hbooks" ofType="com.yj.model.Hbook">
      <result property="bookId" column="book_id"></result>
      <result property="bookName" column="book_name"></result>
      <result property="price" column="price"></result>
    </collection>
  </resultMap>

  <sql id="Base_Column_List" >
    bcid, bid, cid
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_hibernate_book_category
    where bcid = #{bcid,jdbcType=INTEGER}
  </select>

  <select id="queryByBid" resultMap="HbookVoMap" parameterType="java.lang.Integer">
    select * from t_hibernate_book b,t_hibernate_book_category bc,t_hibernate_category c
     where b.book_id = bc.bid and bc.cid = c.category_id and b.book_id = #{bid}
  </select>
  <select id="queryByCid" resultMap="CategoryVoMap" parameterType="java.lang.Integer">
    select * from t_hibernate_book b,t_hibernate_book_category bc,t_hibernate_category c
     where b.book_id = bc.bid and bc.cid = c.category_id and c.category_id=#{cid}
  </select>


  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_hibernate_book_category
    where bcid = #{bcid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.yj.model.HbookCategory" >
    insert into t_hibernate_book_category (bcid, bid, cid
      )
    values (#{bcid,jdbcType=INTEGER}, #{bid,jdbcType=INTEGER}, #{cid,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.yj.model.HbookCategory" >
    insert into t_hibernate_book_category
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bcid != null" >
        bcid,
      </if>
      <if test="bid != null" >
        bid,
      </if>
      <if test="cid != null" >
        cid,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="bcid != null" >
        #{bcid,jdbcType=INTEGER},
      </if>
      <if test="bid != null" >
        #{bid,jdbcType=INTEGER},
      </if>
      <if test="cid != null" >
        #{cid,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.yj.model.HbookCategory" >
    update t_hibernate_book_category
    <set >
      <if test="bid != null" >
        bid = #{bid,jdbcType=INTEGER},
      </if>
      <if test="cid != null" >
        cid = #{cid,jdbcType=INTEGER},
      </if>
    </set>
    where bcid = #{bcid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.yj.model.HbookCategory" >
    update t_hibernate_book_category
    set bid = #{bid,jdbcType=INTEGER},
      cid = #{cid,jdbcType=INTEGER}
    where bcid = #{bcid,jdbcType=INTEGER}
  </update>
</mapper>

测试包:

HbookCategoryServiceImplTest:

package com.yj.service.Impl;

import com.yj.SpringBaseTest;
import com.yj.model.Category;
import com.yj.model.Hbook;
import com.yj.service.HbookCategoryService;
import com.yj.vo.CategoryVo;
import com.yj.vo.HbookVo;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author 仰望天空
 * @site
 * @company xxx公司
 * @create 2019-09-26 21:08
 */
public class HbookCategoryServiceImplTest extends SpringBaseTest {
    @Autowired
    private HbookCategoryService hbookCategoryService;
    @Test
    public void queryByBid() {
        HbookVo hbookVo = hbookCategoryService.queryByBid(1);
        System.out.println(hbookVo);
        for (Category category : hbookVo.getCategories()) {
            System.out.println(category);
        }
    }

    @Test
    public void queryByCid() {
        CategoryVo categoryVo = hbookCategoryService.queryByCid(1);
        System.out.println(categoryVo);
        for (Hbook hbook : categoryVo.getHbooks()) {
            System.out.println(hbook);
        }
    }
}

结果图:
mybatis之关联关系映射
mybatis之关联关系映射

上一篇:mybaits requestMap与requestType,以及对应的注解


下一篇:updateprimarykey 和updateprimaryKeySelective