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中的关联关系配置,并在实际项目中发挥作用。感谢阅读!

匿瘾
+关注
目录
打赏
0
1
1
0
3
分享
相关文章
微服务——MyBatis配置——事务管理
本段内容主要介绍了事务管理的两种类型:JDBC 和 MANAGED。JDBC 类型直接利用数据源连接管理事务,依赖提交和回滚机制;而 MANAGED 类型则由容器全程管理事务生命周期,例如 JEE 应用服务器上下文,默认会关闭连接,但可根据需要设置 `closeConnection` 属性为 false 阻止关闭行为。此外,提到在使用 Spring + MyBatis 时,无需额外配置事务管理器,因为 Spring 模块自带的功能可覆盖上述配置,且这两种事务管理器类型均无需设置属性。
14 0
微服务——MyBatis配置——多环境配置
在 MyBatis 中,多环境配置允许为不同数据库创建多个 SqlSessionFactory。通过传递环境参数给 SqlSessionFactoryBuilder,可指定使用哪种环境;若忽略,则加载默认环境。`environments` 元素定义环境配置,包括默认环境 ID、事务管理器和数据源类型等。每个环境需唯一标识,确保默认环境匹配其中之一。代码示例展示了如何构建工厂及配置 XML 结构。
14 0
微服务——MyBatis配置——常见配置
本文介绍了 MyBatis 的常见配置及其加载顺序。属性配置优先级为:方法参数传递的属性 &gt; resource/url 属性中配置 &gt; properties 元素中指定属性。同时列举了多个关键配置项,如 `cacheEnabled`(全局缓存开关)、`lazyLoadingEnabled`(延迟加载)、`useGeneratedKeys`(使用 JDBC 自动生成主键)等,并详细说明其作用、有效值及默认值。这些配置帮助开发者优化 MyBatis 的性能与行为。
16 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
28 0
MyBatis篇-常见配置
本文介绍了 MyBatis 的常见配置及事务管理相关内容。首先概述了 MyBatis 属性加载顺序,方法参数属性优先级最高。接着列举了几个常见配置属性,如 cacheEnabled、lazyLoadingEnabled 等,并说明其作用与默认值。在多环境配置部分,讲解如何通过 SqlSessionFactoryBuilder 指定环境,以及 environments 元素的配置细节。最后讨论了两种事务管理模式:JDBC 和 MANAGED,分别适用于不同场景,并指出在使用 Spring 模块时无需额外配置事务管理器。
Mybatis一对一,一对多关联查询
## MyBatis一对一、一对多关联查询详解 MyBatis是一款优秀的持久层框架,提供了灵活的SQL映射功能,支持复杂的数据库操作。本文将详细介绍MyBatis中一对一和一对多关联查询的实现。 ### 一对一关联查询 一对一关联关系指的是一个表中的一条记录与另一个表中的一条记录相关联。例如,一个用户有一个地址信息。 #### 数据库表设计 假设有两个表:`user`和 `address`。 ``` CREATE TABLE user ( id INT PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE address
60 18
Mybatis学习:Mybatis缓存配置
MyBatis缓存配置包括一级缓存(事务级)、二级缓存(应用级)和三级缓存(如Redis,跨JVM)。一级缓存自动启用,二级缓存需在`mybatis-config.xml`中开启并配置映射文件或注解。集成Redis缓存时,需添加依赖、配置Redis参数并在映射文件中指定缓存类型。适用于查询为主的场景,减少增删改操作,适合单表操作且表间关联较少的业务。
|
5月前
|
Mybatis中一对一和一对多的处理
这篇文章讲解了在Mybatis中如何处理一对一和一对多的关系映射,包括使用association和collection标签的具体方法。
165 1
MyBatis-Spring配置简单了解
在基本的 MyBatis 中,session 工厂可以使用 SqlSessionFactoryBuilder 来创建。而在 MyBatis-spring 中,则使用 SqlSessionFactoryBean 来替代。
905 0