MyBatis中一对一、一对多和多对多关联关系的配置详解

简介: MyBatis中一对一、一对多和多对多关联关系的配置详解

引言

MyBatis是一款优秀的持久层框架,它提供了灵活且强大的关联关系配置功能。本文将介绍MyBatis中一对一、一对多和多对多关联关系的配置方法和实践经验,帮助读者更好地理解和应用这些关系。

一对一关联关系配置

一对一关联关系表示两个实体之间具有唯一对应关系。在MyBatis中配置一对一关联关系需要使用标签和标签。下面是一个示

一对一关联关系配置

例:

<resultMap id="OrderItemVoMap" type="com.niyin.vo.OrderltemVo">
  <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>
  <association property="order" javaType="com.niyin.model.Order">
    <result column="order_id" property="orderId"></result>
    <result column="order_no" property="orderNo"></result>
  </association>
</resultMap>
  <select id="selectByOrderItem" 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=#{oiid}
  </select>

orderitemMap

package com.niyin.mapper;
import com.niyin.model.Orderitem;
import com.niyin.vo.OrderVo;
import com.niyin.vo.OrderltemVo;
import org.apache.ibatis.annotations.Param;
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);
    OrderltemVo selectByOrderItem(@Param("oiid") Integer oiid);
}

biz

package com.niyin.biz;
import com.niyin.vo.OrderltemVo;
import org.apache.ibatis.annotations.Param;
public interface OrderItemBiz {
    OrderltemVo selectByOrderItem(Integer oiid);
}

impl

package com.niyin.biz.impl;
import com.niyin.biz.OrderItemBiz;
import com.niyin.mapper.OrderitemMapper;
import com.niyin.vo.OrderltemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderItemBizImpl implements OrderItemBiz {
    @Autowired
    private OrderitemMapper orderitemMapper;
    @Override
    public OrderltemVo selectByOrderItem(Integer oiid) {
        return orderitemMapper.selectByOrderItem(oiid);
    }
}

测试

package com.niyin.biz.impl;
import com.niyin.biz.Hboobiz;
import com.niyin.biz.HcategoryBiz;
import com.niyin.biz.OrderBiz;
import com.niyin.biz.OrderItemBiz;
import com.niyin.vo.CategoryVo;
import com.niyin.vo.HbookVo;
import com.niyin.vo.OrderVo;
import com.niyin.vo.OrderltemVo;
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;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
public class OrderBizImplTest {
    @Autowired
    private OrderBiz orderBiz;
@Autowired
private OrderItemBiz orderItemBiz;
@Autowired
private Hboobiz hboobiz;
@Autowired
private HcategoryBiz hcategoryBiz;
    @Test
    public void selectByOid() {
       OrderVo orderVo= orderBiz.selectByOid(7);
        System.out.println(orderVo);
        orderVo.getOrderitems().forEach(System.out::println);
    }
@Test
    public void selectByOItem() {
   OrderltemVo orderltemVo= orderItemBiz.selectByOrderItem(27);
    System.out.println(orderltemVo);
    System.out.println(orderltemVo.getOrder());
}
@Test
    public void selectBybook(){
    HbookVo hbookVo = this.hboobiz.selectByBookID(8);
hbookVo.getCategories().forEach(System.out::println);
}
    @Test
    public void selectBcid(){
        CategoryVo categoryVo = this.hcategoryBiz.selectBycategoryId(8);
        System.out.println(categoryVo);
        categoryVo.getBooks().forEach(System.out::println);
    }
    }

下面案列均用这个测试类

结果

上述代码中,定义了orderitem实体的映射规则,表示与User实体关联的Profile实体,通过property属性指定了关联属性的名称,通过javaType属性指定了关联属性的类型。在SQL查询语句中,可以通过JOIN操作获取关联实体的数据。

一对多关联关系配置

一对多关联关系表示一个实体与多个实体之间存在关联关系。在MyBatis中配置一对多关联关系需要使用标签和标签。下面是一个示例:

<resultMap id="OrderVoMap" type="com.niyin.vo.OrderVo" >
   <result column="order_id" property="orderId"></result>
    <result column="order_no" property="orderNo"></result>
    <collection property="orderitems" ofType="com.niyin.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>
<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>

vo

package com.niyin.vo;
import com.niyin.model.Order;
import com.niyin.model.Orderitem;
import java.util.ArrayList;
import java.util.List;
public class OrderVo extends Order {
private List<Orderitem> orderitems =new ArrayList<Orderitem>();
    public List<Orderitem> getOrderitems() {
        return orderitems;
    }
    public void setOrderitems(List<Orderitem> orderitems) {
        this.orderitems = orderitems;
    }
}

map

package com.niyin.mapper;
import com.niyin.model.Order;
import com.niyin.vo.OrderVo;
import org.apache.ibatis.annotations.Param;
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);
}

biz

package com.niyin.biz;
import com.niyin.vo.OrderVo;
import org.apache.ibatis.annotations.Param;
public interface OrderBiz  {
    OrderVo selectByOid(Integer oid);
}

impl

package com.niyin.biz.impl;
import com.niyin.biz.OrderBiz;
import com.niyin.mapper.OrderMapper;
import com.niyin.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);
    }
}

结果

结论

上述代码中,定义了Post实体的映射规则,表示与Post实体关联的Comment实体集合,通过property属性指定了关联属性的名称,通过ofType属性指定了集合中元素的类型。在SQL查询语句中,可以利用外键约束和嵌套查询等方式获取关联实体集合的数据。

多对多关联关系配置

多对多关联关系表示两个实体之间存在互相包含的关系。在MyBatis中配置多对多关联关系需要使用中间表和联合主键。下面是一个示例:

<resultMap id="HbookMap" type="com.niyin.vo.HbookVo" >
<result column="book_id" property="bookId"></result>
    <result column="book_name" property="bookName"></result>
    <result column="price" property="price"></result>
    <collection property="categories" ofType="com.niyin.model.HCategory">
      <result column="category_id" property="categoryId"></result>
      <result column="category_name" property="categoryName"></result>
    </collection>
  </resultMap>
  <select id="selectByBookID" resultMap="HbookMap" 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>

vo

package com.niyin.vo;
import com.niyin.model.HBook;
import com.niyin.model.HCategory;
import java.util.List;
public class HbookVo extends HBook {
    private List<HCategory> categories;
    public List<HCategory> getCategories() {
        return categories;
    }
    public void setCategories(List<HCategory> categories) {
        this.categories = categories;
    }
}

map

package com.niyin.mapper;
import com.niyin.model.HBook;
import com.niyin.vo.HbookVo;
import org.apache.ibatis.annotations.Param;
public interface HBookMapper {
    int deleteByPrimaryKey(Integer bookId);
    int insert(HBook record);
    int insertSelective(HBook record);
    HBook selectByPrimaryKey(Integer bookId);
    int updateByPrimaryKeySelective(HBook record);
    int updateByPrimaryKey(HBook record);
    HbookVo selectByBookID(@Param("bid") Integer bid) ;
}

biz

package com.niyin.biz;
import com.niyin.vo.HbookVo;
import org.apache.ibatis.annotations.Param;
public interface Hboobiz {
    HbookVo selectByBookID( Integer bid) ;
}

impl

package com.niyin.biz;
import com.niyin.vo.HbookVo;
import org.apache.ibatis.annotations.Param;
public interface Hboobiz {
    HbookVo selectByBookID( Integer bid) ;
}

运行结果

示例2:

<resultMap id="categoryvoMap" type="com.niyin.vo.CategoryVo">
    <result column="category_id" property="categoryId"></result>
    <result column="category_name" property="categoryName"></result>
    <collection property="books" ofType="com.niyin.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="selectBycategoryId" 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>

vo

package com.niyin.vo;
import com.niyin.model.HBook;
import com.niyin.model.HCategory;
import java.util.ArrayList;
import java.util.List;
public class CategoryVo extends HCategory {
    private List<HBook>books=new ArrayList<>();
    public List<HBook> getBooks() {
        return books;
    }
    public void setBooks(List<HBook> books) {
        this.books = books;
    }
}

map

package com.niyin.mapper;
import com.niyin.model.HCategory;
import com.niyin.vo.CategoryVo;
import org.apache.ibatis.annotations.Param;
public interface HCategoryMapper {
    int deleteByPrimaryKey(Integer categoryId);
    int insert(HCategory record);
    int insertSelective(HCategory record);
    HCategory selectByPrimaryKey(Integer categoryId);
    int updateByPrimaryKeySelective(HCategory record);
    int updateByPrimaryKey(HCategory record);
    CategoryVo selectBycategoryId(@Param("cid") Integer cid);
}

biz

package com.niyin.biz;
import com.niyin.vo.CategoryVo;
import org.apache.ibatis.annotations.Param;
public interface HcategoryBiz {
    CategoryVo selectBycategoryId(Integer cid);
}

impl

package com.niyin.biz.impl;
import com.niyin.biz.HcategoryBiz;
import com.niyin.mapper.HCategoryMapper;
import com.niyin.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HcategoryBizImpl implements HcategoryBiz {
    @Autowired
    private HCategoryMapper hCategoryMapper;
    @Override
    public CategoryVo selectBycategoryId(Integer cid) {
        return hCategoryMapper.selectBycategoryId(cid);
    }
}

结果

上述代码中,定义了User实体和Role实体的映射规则,并通过property属性指定了互相关联的属性名称。在SQL查询语句中,需要通过联合主键和中间表来获取两个实体之间的关联数据。

结论

本文介绍了MyBatis中一对一、一对多和多对多关联关系的配置方法和实践经验。在一对一关联关系中,使用标签配置关联属性映射;在一对多关联关系中,使用标签配置关联集合属性映射;在多对多关联关系中,需要通过中间表和联合主键来配置关联关系。通过灵活运用这些配置方法,可以轻松处理各种复杂的关联查询需求。

希望本文能够帮助读者更好地理解和应用MyBatis中的关联关系配置,并在实际项目中发挥作用。感谢阅读!

目录
相关文章
|
6天前
|
SQL XML Java
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
文章介绍了MyBatis中高级查询的一对多和多对一映射处理,包括创建数据库表、抽象对应的实体类、使用resultMap中的association和collection标签进行映射处理,以及如何实现级联查询和分步查询。此外,还补充了延迟加载的设置和用法。
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
|
6天前
|
SQL XML Java
mybatis复习01,简单配置让mybatis跑起来
文章介绍了MyBatis的基本概念、历史和特点,并详细指导了如何配置MyBatis环境,包括创建Maven项目、添加依赖、编写核心配置文件、创建数据表和实体类、编写Mapper接口和XML配置文件,以及如何编写工具类和测试用例。
mybatis复习01,简单配置让mybatis跑起来
|
2月前
|
安全 Java 数据库连接
后端框架的学习----mybatis框架(3、配置解析)
这篇文章详细介绍了MyBatis框架的核心配置文件解析,包括环境配置、属性配置、类型别名设置、映射器注册以及SqlSessionFactory和SqlSession的生命周期和作用域管理。
后端框架的学习----mybatis框架(3、配置解析)
|
1月前
|
SQL XML Java
mybatis :sqlmapconfig.xml配置 ++++Mapper XML 文件(sql/insert/delete/update/select)(增删改查)用法
当然,这些仅是MyBatis功能的初步介绍。MyBatis还提供了高级特性,如动态SQL、类型处理器、插件等,可以进一步提供对数据库交互的强大支持和灵活性。希望上述内容对您理解MyBatis的基本操作有所帮助。在实际使用中,您可能还需要根据具体的业务要求调整和优化SQL语句和配置。
30 1
|
2月前
|
Java 数据库连接 mybatis
后端框架的学习----mybatis框架(9、多对一处理和一对多处理)
这篇文章介绍了在MyBatis框架中如何处理多对一和一对多的关联查询,通过定义`<resultMap>`和使用`<association>`与`<collection>`元素来实现对象间的关联映射。
|
2月前
|
缓存 Java 数据库连接
mybatis1.常见配置
本文介绍了MyBatis框架中的常见配置及其加载顺序。配置可通过`properties`元素、资源文件或方法参数传递,其中方法参数传递的属性具有最高优先级。文章列举了几个重要的配置项,如`cacheEnabled`用于全局开启或关闭缓存功能;`lazyLoadingEnabled`控制对象的延迟加载行为;`useGeneratedKeys`允许JDBC支持自动生成主键;`defaultExecutorType`设定默认执行器类型等。此外,还介绍了多环境配置方法,通过`environments`元素可定义不同环境下的数据库连接信息,并可根据需求动态选择加载特定环境
|
3月前
|
SQL Java 数据库连接
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
59 3
若依修改,集成mybatisplus报错,若依集成mybatisplus,总是找不到映射是怎么回事只要是用mp的方法就找报,改成mybatisPlus配置一定要改
若依修改,集成mybatisplus报错,若依集成mybatisplus,总是找不到映射是怎么回事只要是用mp的方法就找报,改成mybatisPlus配置一定要改
接口模板,文本常用的接口Controller层,常用的controller层模板,Mybatisplus的相关配置
接口模板,文本常用的接口Controller层,常用的controller层模板,Mybatisplus的相关配置
|
19天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)