前言:
在我们之前的hibernate中我们是学过了关联关系的,
所以我们在本章给讲一讲mybatis的关联关系。

mybatis的关联关系
一对多的测试
1.通过逆向工程生成Hbook,HbookCategory,Category
如何生成,可以参考之前的
这次我们要用到五张数据库表

<table schema="" tableName="t_hibernate_order" domainObjectName="Order"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false"> </table>
<table schema="" tableName="t_hibernate_order_item" domainObjectName="OrderItem"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false"> </table>
<table schema="" tableName="t_hibernate_book" domainObjectName="Hbook"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false"> </table>
<table schema="" tableName="t_hibernate_category" domainObjectName="Category"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false"> </table>
<table schema="" tableName="t_hibernate_book_category" domainObjectName="HbookCategory"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false"> </table>

生成之后目录

OrderVo

package com.jt.model.vo;

import com.jt.model.Orde;
import com.jt.model.OrdeItem; import java.util.ArrayList;
import java.util.List; /**
* @author jt
* @site www.xiaomage.com
* @company xxx公司
* @create  2019-10-23 18:59
*/
public class OrderVo extends Orde {
private List<OrdeItem> orderItems=new ArrayList<>(); public List<OrdeItem> getOrderItems() {
return orderItems;
} public void setOrderItems(List<OrdeItem> orderItems) {
this.orderItems = orderItems;
}
}

OrderItemVo

package com.jt.model.vo;

import com.jt.model.Orde;
import com.jt.model.OrdeItem; /**
* @author jt
* @site www.xiaomage.com
* @company xxx公司
* @create  2019-10-23 19:01
*/
public class OrderItemVo extends OrdeItem {
private Orde orde; public Orde getOrde() {
return orde;
} public void setOrde(Orde orde) {
this.orde = orde;
}
}

CategoryVo

package com.jt.model.vo;

import com.jt.model.Category;
import com.jt.model.Hbook; import java.util.ArrayList;
import java.util.List; /**
* @author jt
* @site www.xiaomage.com
* @company xxx公司
* @create  2019-10-23 20:08
*/
public class CategoryVo extends Category {
private List<Hbook> hbooks=new ArrayList<>(); public List<Hbook> getHbooks() {
return hbooks;
} public void setHbooks(List<Hbook> hbooks) {
this.hbooks = hbooks;
}
}

HbookVo

package com.jt.model.vo;

import com.jt.model.Category;
import com.jt.model.Hbook; import java.util.ArrayList;
import java.util.List; /**
* @author jt
* @site www.xiaomage.com
* @company xxx公司
* @create  2019-10-23 20:06
*/
public class HbookVo extends Hbook {
private List<Category> categories=new ArrayList<>(); // public List<Category> getCategories() {
// return categories;
// }
//
// public void setCategories(List<Category> categories)
// {
// this.categories = categories;
// } public List<Category> getCategories() {
return categories;
} public void setCategories(List<Category> categories) {
this.categories = categories;
}
}

4.做一个测试(根据id来查询)

 @Test
public void selectByOrderItemId() {
List<OrderItemVo> orderItemVos = oneToManyService.selectByOrderItemId();
OrderItemVo orderItemVo=orderItemVos.get();
System.out.println(orderItemVo);
System.out.println(orderItemVo.getOrde());
} @Test
public void selectByOrderId() {
List<OrderVo> orderVos = oneToManyService.selectByOrderId();
OrderVo orderVo=orderVos.get();
// System.out.println(orderVos.size());
System.out.println(orderVo);
for (OrdeItem orderItem : orderVo.getOrderItems()) {
System.out.println(orderItem);
}
}

通过一个订单项的id,查询出订单项信息的同时,查询出所属的订单

通过一个订单id,查询出订单信息的同时,查询出所有的订单项

2、多对多关联关系

首先先用逆向生成工具生成t_hibernate_book、t_hibernate_book_category(可生成可不生成)、t_hibernate_category,这两张表对应的model与mapper
generatorConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置-->
<classPathEntry location="D:\\initpath\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/> <!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator> <!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver> <!-- 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.jt.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator> <!-- 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.jt.mapper"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator> <!-- 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.jt.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator> <!-- 配置表信息 -->
<!-- schema即为数据库名 -->
<!-- tableName为对应的数据库表 -->
<!-- domainObjectName是要生成的实体类 -->
<!-- enable*ByExample是否生成 example类 -->
<!--<table schema="" tableName="t_book" domainObjectName="Book"-->
<!--enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false">-->
<!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
<!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
<!--&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;-->
<!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
<!--</table>--> <!-- <table schema="" tableName="t_hibernate_order" domainObjectName="Orde"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;
&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;
&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;
&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;
</table>--> <!--<table schema="" tableName="t_hibernate_order_item" domainObjectName="OrdeItem"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;
&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;
&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;
&lt;!&ndash; < columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;
</table>--> <table schema="" tableName="t_hibernate_book`" domainObjectName="Hbook"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
<!-- 忽略列,不生成bean 字段 -->
<!-- <ignoreColumn column="FRED" /> -->
<!-- 指定列的java数据类型 -->
<!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
</table> <!--<table schema="" tableName="t_hibernate_category" domainObjectName="Category"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;
&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;
&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;
&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;
</table>--> <!-- <table schema="" tableName="t_hibernate_book_category" domainObjectName="HbookCategory"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;
&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;
&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;
&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;
</table>--> </context>
</generatorConfiguration>

HBookMapper

package com.jt.mapper;

import com.jt.model.Hbook;
import com.jt.model.vo.HbookVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository; @Repository
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 selectByBid(@Param("bid") Integer bid);
}

HBookMapper.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.jt.mapper.HbookMapper" >
<resultMap id="BaseResultMap" type="com.jt.model.Hbook" >
<constructor >
<idArg column="book_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="book_name" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
</constructor>
</resultMap> <resultMap id="HbookVoMap" type="com.jt.model.vo.HbookVo">
<result property="bookId" column="book_id"></result>
<result property="bookName" column="book_name"></result>
<result property="price" column="price"></result>
<!-- <result property="orderItems"></result>-->
<collection property="categories" ofType="com.jt.model.Category">
<result property="categoryId" column="category_id"></result>
<result property="categoryName" column="category_name"></result>
</collection>
</resultMap> <sql id="Base_Column_List" >
book_id, book_name, price
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_hibernate_book
where book_id = #{bookId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_hibernate_book
where book_id = #{bookId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.jt.model.Hbook" >
insert into t_hibernate_book (book_id, book_name, price
)
values (#{bookId,jdbcType=INTEGER}, #{bookName,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
)
</insert>
<insert id="insertSelective" parameterType="com.jt.model.Hbook" >
insert into t_hibernate_book
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="bookId != null" >
book_id,
</if>
<if test="bookName != null" >
book_name,
</if>
<if test="price != null" >
price,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="bookId != null" >
#{bookId,jdbcType=INTEGER},
</if>
<if test="bookName != null" >
#{bookName,jdbcType=VARCHAR},
</if>
<if test="price != null" >
#{price,jdbcType=REAL},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.jt.model.Hbook" >
update t_hibernate_book
<set >
<if test="bookName != null" >
book_name = #{bookName,jdbcType=VARCHAR},
</if>
<if test="price != null" >
price = #{price,jdbcType=REAL},
</if>
</set>
where book_id = #{bookId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.jt.model.Hbook" >
update t_hibernate_book
set book_name = #{bookName,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL}
where book_id = #{bookId,jdbcType=INTEGER}
</update> <select id="selectByBid" resultMap="HbookVoMap" >
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>
</mapper>

HBookCategoryMapper

package com.jt.mapper;

import com.jt.model.HbookCategory;

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

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.jt.mapper.HbookCategoryMapper" >
<resultMap id="BaseResultMap" type="com.jt.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>
<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>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_hibernate_book_category
where bcid = #{bcid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.jt.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.jt.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.jt.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.jt.model.HbookCategory" >
update t_hibernate_book_category
set bid = #{bid,jdbcType=INTEGER},
cid = #{cid,jdbcType=INTEGER}
where bcid = #{bcid,jdbcType=INTEGER}
</update>
</mapper>

测试方法

   @Autowired
private ManyToManyService manyToManyService; @Test
public void selectByBid() {
HbookVo hbookVo = manyToManyService.selectByBid();
System.out.println(hbookVo);
for (Category category : hbookVo.getCategories()) {
System.out.println(category);
}
} @Test
public void selectByCid() {
CategoryVo categoryVo=this.manyToManyService.selectByCid();
System.out.println(categoryVo);
for (Hbook hbook : categoryVo.getHbooks()) {
System.out.println(hbook);
}
}

mybatis之关联关系的更多相关文章

  1. mybatis一对一关联关系映射

    mybatis一对一关联关系映射 在关联关系中,有一对一,一对多,多对多三种关联关系. 一对一关系:在操作上,任意一方引入对方的主键作为外键. 一对多关系:在"多"的一方添加&qu ...

  2. MyBatis对象关联关系---- association与collection

    Mybatis处理“一对多”的关系时,需要用到associasion元素.处理”多对一“用collection元素来实现(这两个元素在之前mapper文件中提到过). 本例子中,假设一名User可以有 ...

  3. mybatis之关联关系映射

    Mybatis关联关系映射 1.一对多 首先先用逆向生成工具生成t_hibernate_order.t_hibernate_order_item 这两张表对应的model与mapper OrderVo ...

  4. MyBatis的关联关系补充 多对多 继承

    多对多 一个学生有多个课程 一个课程有多个学生 思路分析 :使用一个中间表 用学生表和课程表的主键作为中间表的联合主键 1数据库表的设计 课程表 学生表 中间表 2/实体类的设计 课程类 public ...

  5. MyBatis的关联关系 一对一 一对多 多对多

    一对一示例 一个妻子对应一个丈夫 数据库表设计时 在妻子表中添加一个丈夫主键的作为外键 1 对应的JavaBean代码虽然在数据库里只有一方配置的外键,但是这个一对一是双向的关系. Husband实体 ...

  6. Mybatis之关联关系(一对多、多对多)

    目的: Mybatis关系映射之一对多 Mybatis关系映射之多对多 Mybatis关系映射之一对多 一对多 (订单对应多个订单项) 多对一  (订单项对应一个订单) 其是映射关系的基层思维是一样的 ...

  7. MyBatis对象关联关系----多对多的保存与查询

    模拟情景: 对象:学生,课程 关系:一个学生可选多个课程,一门课程可被多个学生选择 一.保存 1.创建数据库表,student,course,student_course,其中student_cour ...

  8. mybatis学习笔记三(关联关系)

    学习mybatis的关联关系,主要注解在代码上,这里不做解释.配置文件一样的就不贴了 1.关联关系表创建(学生对应老师 多对一) 学生老师表 2.表对应的实体类 package com.home.en ...

  9. Mybatis的关联映射案例

    主要是对之前学习的关联映射做一个案例,自己动手实践一下,可以理解的更好一点. 开发环境 开发工具:idea Java环境: jdk1.8.0_121 数据库:SQLServer 项目结构,里面包含了三 ...

随机推荐

  1. mysql5.5下载安装教程

    下载地址:https://dev.mysql.com/downloads/mysql/ 这里选择的是5.5的版本: 步骤1: 步骤2: 步骤三: 步骤四: 步骤5: 步骤6: 步骤7: 步骤8: 步骤 ...

  2. Android8.1 SystemUI源码分析之 电池时钟刷新

    SystemUI源码分析相关文章 Android8.1 SystemUI源码分析之 Notification流程 分析之前再贴一下 StatusBar 相关类图 电池图标刷新 从上篇的分析得到电池图标 ...

  3. KVO-键值监听

    键值监听,就是可以监听对象某个属性值的变化: 首先,在工程中,新建一个Person的类 @interface Person : NSObject @property (nonatomic, copy) ...

  4. Windows添加自定义开机用户登录启动程序

    默认的启动程序 Ctrl+shift -> Esc调用任务管理器-->启动项选项即可完成计算机开机自启动选项,不过这里只有系统默认添加的. 添加自定义开机启动程序 Windows+R调用运 ...

  5. s3c2440裸机-内存控制器(四、SDRAM原理-cpu是如何访问sdram的)

    1.SDRAM原理 black (1)SDRAM内部存储结构: (2)再看看与2440连接的SDRAM原理图: sdram引脚说明: A0-A12:地址总线 D0-D15:数据总线(位宽16,2片级联 ...

  6. 27.t分布随机近邻嵌入t-SNE

    t分布随机近邻嵌入(t-distributed Stohastic Neighbor Embedding) 基本思路:为高维特征空间在二维平面(或三维超平面,不过基本上总是使用二维空间)上寻找一个投影 ...

  7. mysql分组报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

    环境:Server version: 5.7.27-0 ubuntu 18.04.1 (Ubuntu) 执行分组语句:select * from pet group by owner;时报错: mys ...

  8. linux常用命令总结篇

    关于linux的一些基础命令,以前也学过,但是长时间不用还是感觉生疏了,所以记录下来以便后期温故知新. 1. cd:cd命令用来切换工作目录至dirname.cd ~ 进入用户主目录,cd - 进入之 ...

  9. Git教程---由浅入深

    初学者很难找到一个由浅入深,学完后能立刻上手的Git教程 Git用户 V&Git专家 Git是一个工具,是目前世界上最先进的分布式版本控制系统(没有之一). 集中式的版本控制系统  V& ...

  10. 关于使用宏将csv批量转换成xls的分享

    最近在使用遇到一个问题需要把csv格式的文件转成xls,随便新建一个excel,然后打开,选择“开发工具”,找到下图“宏”,如果跟下图一样的话就需要先启用宏,启用之后可以直接把下面的代码直接复制到代码 ...