“MyBatis中的关联关系配置与多表查询“

简介: “MyBatis中的关联关系配置与多表查询“

引言

在数据库应用开发中,经常会遇到需要查询多个表之间的关联关系的情况。MyBatis是一个流行的Java持久层框架,它提供了灵活的配置方式来处理多表查询中的一对多、一对一和多对多关系。本文将介绍如何在MyBatis中配置和使用这些关联关系。

一、一对多关系配置

在数据库中,一对多关系是指一个表的一条记录对应另一个表的多条记录。在MyBatis中,我们可以通过以下步骤来配置和使用一对多关系:

  1. 创建实体类
    首先,我们需要创建两个实体类,分别表示一对多关系中的一方和多方。例如,我们创建一个Order类和一个OrderItem类,其中一个订单可以对应多个订单项。
public class Order {
    private Long id;
    private String orderNo;
    private List<OrderItem> orderItems;
    // 省略getter和setter方法
}
public class OrderItem {
    private Long id;
    private String productName;
    // 省略getter和setter方法
}
package com.yuan.vo;
import com.yuan.model.Order;
import com.yuan.model.OrderItem;
import java.util.ArrayList;
import java.util.List;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-01 11:48
 */
public class OrderVO extends Order {
    private List<OrderItem> list = new ArrayList<>();
    public List<OrderItem> getList() {
        return list;
    }
    public void setList(List<OrderItem> list) {
        this.list = list;
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39
• 40
  1. 创建Mapper接口和XML文件
    接下来,我们需要创建Mapper接口和对应的XML文件来定义查询方法和SQL语句。在XML文件中,我们可以使用MyBatis的标签来配置一对多关系。
<!-- OrderMapper.xml -->
<mapper namespace="com.yuan.mapper.OrderMapper">
    <resultMap id="OrderVoMap" type="com.yuan.vo.OrderVO" >
    <result column="order_id" property="orderId"></result>
    <result column="order_no" property="orderNo"></result>
    <collection property="list" ofType="com.yuan.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="demo1" resultMap="OrderVoMap" parameterType="java.lang.Integer" >
    select * from t_hibernate_order o ,t_hibernate_order_item oit where o.order_id = oit.oid and o.order_id = #{oid}
  </select>
</mapper>
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
  1. 编写查询方法
    最后,我们在Mapper接口中定义查询方法,并在XML文件中配置对应的SQL语句。
package com.yuan.Biz;
import com.yuan.vo.OrderVO;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-01 13:08
 */
public interface OrderBiz {
    OrderVO demo1(Integer oid);
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
  1. 使用一对多关系查询
    现在,我们可以在代码中使用一对多关系查询了。
package com.yuan.Biz.Impl;
import com.yuan.Biz.OrderBiz;
import com.yuan.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
 * @company 卓京公司
 * @create 2023-09-01 13:13
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
public class OrderBizImplTest {
    @Autowired
    private  OrderBiz orderBiz;
    @Test
    public void demo1() {
        OrderVO orderVO = orderBiz.demo1(7);
        System.out.println(orderVO);
        orderVO.getList().forEach(System.out::println);
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31
• 32

二、一对一关系配置

  1. 创建实体类
    首先,我们需要创建两个实体类,分别表示一对多关系中的一方和一方。例如,我们创建一个Order类和一个OrderItem类,其中一个订单可以对应一个订单项。
public class Order {
    private Long id;
    private String orderNo;
    private List<OrderItem> orderItems;
    // 省略getter和setter方法
}
public class OrderItem {
    private Long id;
    private String productName;
    // 省略getter和setter方法
}
package com.yuan.vo;
import com.yuan.model.Order;
import com.yuan.model.OrderItem;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-01 13:58
 */
public class OrderItemVo extends OrderItem {
   private Order order;
    public Order getOrder() {
        return order;
    }
    public void setOrder(Order order) {
        this.order = order;
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
  1. 创建Mapper接口和XML文件
    接下来,我们需要创建Mapper接口和对应的XML文件来定义查询方法和SQL语句。在XML文件中,我们可以使用MyBatis的标签来配置一对一关系。
<resultMap id="OrderItemVoMap" type="com.yuan.vo.OrderItemVo">
    <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.yuan.model.Order">
      <result column="order_id" property="orderId"></result>
      <result column="order_no" property="orderNo"></result>
    </association>
  </resultMap>
  <select id="demo2" resultMap="OrderItemVoMap" parameterType="java.lang.Integer" >
    select * from t_hibernate_order o ,t_hibernate_order_item oit where o.order_id = oit.oid and oit.order_item_id = #{oiid}
  </select>
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
  1. 编写查询方法
    最后,我们在Mapper接口中定义查询方法,并在XML文件中配置对应的SQL语句。
package com.yuan.Biz;
import com.yuan.model.OrderItem;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-01 14:03
 */
public interface OrderItemBiz {
    OrderItem demo2( Integer oiid);
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
  1. 使用一对一关系查询
    现在,我们可以在代码中使用一对多关系查询了。
package com.yuan.Biz.Impl;
import com.yuan.Biz.OrderItemBiz;
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
 * @company 卓京公司
 * @create 2023-09-01 14:06
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
public class OrderItemBizImplTest {
    @Autowired
    private OrderItemBiz orderItemBiz;
    @Test
    public void demo2() {
        System.out.println(orderItemBiz.demo2(27));
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27

三、多对多关系配置

在数据库中,多对多关系是指两个表之间存在多对多的关系。在MyBatis中,我们可以通过以下步骤来配置和使用多对多关系:

  1. 创建实体类
    首先,我们需要创建两个实体类,分别表示多对多关系中的两个表。例如,我们创建一个User类和一个Role类,一个用户可以拥有多个角色,一个角色也可以被多个用户拥有。
package com.yuan.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;
    }
}
package com.yuan.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.yuan.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.yuan.vo;
import com.yuan.model.HBook;
import com.yuan.model.HCategory;
import java.util.List;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-01 20:35
 */
public class HbookVo extends HBook {
    private List<HCategory> categories ;
    public List<HCategory> getCategories() {
        return categories;
    }
    public void setCategories(List<HCategory> categories) {
        this.categories = categories;
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29
• 30
• 31
• 32
• 33
• 34
• 35
• 36
• 37
• 38
• 39
• 40
• 41
• 42
• 43
• 44
• 45
• 46
• 47
• 48
• 49
• 50
• 51
• 52
• 53
• 54
• 55
• 56
• 57
• 58
• 59
• 60
• 61
• 62
• 63
• 64
• 65
• 66
• 67
• 68
• 69
• 70
• 71
• 72
• 73
• 74
• 75
• 76
• 77
• 78
• 79
• 80
• 81
• 82
• 83
• 84
• 85
• 86
• 87
• 88
• 89
• 90
• 91
• 92
• 93
• 94
• 95
• 96
• 97
• 98
• 99
• 100
• 101
• 102
• 103
• 104
• 105
• 106
• 107
• 108
• 109
• 110
• 111
• 112
• 113
• 114
• 115
• 116
• 117
• 118
• 119
• 120
• 121
• 122
• 123
• 124
• 125
• 126
• 127
• 128
• 129
• 130
• 131
• 132
• 133
• 134
• 135
• 136
• 137
• 138
• 139
• 140
• 141
• 142
• 143
• 144
• 145
• 146
• 147
• 148
• 149
• 150
• 151
• 152
• 153
• 154
• 155
• 156
  1. 创建Mapper接口和XML文件
    接下来,我们需要创建Mapper接口和对应的XML文件来定义查询方法和SQL语句。在XML文件中,我们可以使用MyBatis的标签来配置多对多关系。
<resultMap id="HookVoMap" type="com.yuan.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.yuan.model.HCategory">
      <result column="category_id" property="categoryId"></result>
      <result column="category_name" property="categoryName"></result>
    </collection>
  </resultMap>
  <select id="demo3" resultMap="HookVoMap" 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>
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
  1. 编写查询方法
    最后,我们在Mapper接口中定义查询方法,并在XML文件中配置对应的SQL语句。
package com.yuan.Biz.Impl;
import com.yuan.Biz.HBookBiz;
import com.yuan.mapper.HBookMapper;
import com.yuan.vo.HbookVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-01 21:23
 */
@Service
public class HBookBizImpl implements HBookBiz {
    @Autowired
    private HBookMapper hBookMapper;
    @Override
    public HbookVo demo3(Integer bid) {
        return hBookMapper.demo3(bid);
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
  1. 使用多对多关系查询
    现在,我们可以在代码中使用多对多关系查询了。
package com.yuan.Biz.Impl;
import com.yuan.Biz.HBookBiz;
import com.yuan.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
 * @company 卓京公司
 * @create 2023-09-01 21:24
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
public class HBookBizImplTest {
    @Autowired
    private HBookBiz hBookBiz;
    @Test
    public void demo3() {
        HbookVo hbookVo = hBookBiz.demo3(8);
        System.out.println(hbookVo);
        hbookVo.getCategories().forEach(System.out::println);
    }
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22
• 23
• 24
• 25
• 26
• 27
• 28
• 29

总结

本文介绍了在MyBatis中配置和使用一对多和多对多关系的方法。通过合理的实体类设计、Mapper接口和XML文件的配置,我们可以方便地进行多表查询,并丰富了应用程序的功能和灵活性。

补充内容:在实际开发中,我们还可以使用MyBatis的动态SQL和缓存等特性来进一步优化查询性能和提高开发效率。希望本文对您在MyBatis中处理关联关系有所帮助。


相关文章
|
XML Java 数据库连接
MyBatis的常见配置
MyBatis 常见配置包括数据库连接、类型别名、映射器等核心模块,合理配置可提升开发效率与系统性能。主要内容涵盖核心配置文件结构、关键配置项详解及配置优先级说明。
1030 4
|
Oracle 关系型数据库 Java
【YashanDB知识库】Mybatis-Plus适配崖山配置
【YashanDB知识库】Mybatis-Plus适配崖山配置
|
Java 数据库连接 微服务
微服务——MyBatis配置——事务管理
本段内容主要介绍了事务管理的两种类型:JDBC 和 MANAGED。JDBC 类型直接利用数据源连接管理事务,依赖提交和回滚机制;而 MANAGED 类型则由容器全程管理事务生命周期,例如 JEE 应用服务器上下文,默认会关闭连接,但可根据需要设置 `closeConnection` 属性为 false 阻止关闭行为。此外,提到在使用 Spring + MyBatis 时,无需额外配置事务管理器,因为 Spring 模块自带的功能可覆盖上述配置,且这两种事务管理器类型均无需设置属性。
348 0
|
Java 数据库连接 数据库
微服务——MyBatis配置——多环境配置
在 MyBatis 中,多环境配置允许为不同数据库创建多个 SqlSessionFactory。通过传递环境参数给 SqlSessionFactoryBuilder,可指定使用哪种环境;若忽略,则加载默认环境。`environments` 元素定义环境配置,包括默认环境 ID、事务管理器和数据源类型等。每个环境需唯一标识,确保默认环境匹配其中之一。代码示例展示了如何构建工厂及配置 XML 结构。
327 0
|
缓存 Java 数据库连接
微服务——MyBatis配置——常见配置
本文介绍了 MyBatis 的常见配置及其加载顺序。属性配置优先级为:方法参数传递的属性 &gt; resource/url 属性中配置 &gt; properties 元素中指定属性。同时列举了多个关键配置项,如 `cacheEnabled`(全局缓存开关)、`lazyLoadingEnabled`(延迟加载)、`useGeneratedKeys`(使用 JDBC 自动生成主键)等,并详细说明其作用、有效值及默认值。这些配置帮助开发者优化 MyBatis 的性能与行为。
345 0
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
768 18
|
缓存 NoSQL Java
Mybatis学习:Mybatis缓存配置
MyBatis缓存配置包括一级缓存(事务级)、二级缓存(应用级)和三级缓存(如Redis,跨JVM)。一级缓存自动启用,二级缓存需在`mybatis-config.xml`中开启并配置映射文件或注解。集成Redis缓存时,需添加依赖、配置Redis参数并在映射文件中指定缓存类型。适用于查询为主的场景,减少增删改操作,适合单表操作且表间关联较少的业务。
557 6
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
2161 0
|
缓存 Java 数据库连接
MyBatis篇-常见配置
本文介绍了 MyBatis 的常见配置及事务管理相关内容。首先概述了 MyBatis 属性加载顺序,方法参数属性优先级最高。接着列举了几个常见配置属性,如 cacheEnabled、lazyLoadingEnabled 等,并说明其作用与默认值。在多环境配置部分,讲解如何通过 SqlSessionFactoryBuilder 指定环境,以及 environments 元素的配置细节。最后讨论了两种事务管理模式:JDBC 和 MANAGED,分别适用于不同场景,并指出在使用 Spring 模块时无需额外配置事务管理器。
mybatis复习01,简单配置让mybatis跑起来
文章介绍了MyBatis的基本概念、历史和特点,并详细指导了如何配置MyBatis环境,包括创建Maven项目、添加依赖、编写核心配置文件、创建数据表和实体类、编写Mapper接口和XML配置文件,以及如何编写工具类和测试用例。
mybatis复习01,简单配置让mybatis跑起来