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

Mybatis处理“一对多”的关系时,需要用到associasion元素。处理”多对一“用collection元素来实现(这两个元素在之前mapper文件中提到过)。

本例子中,假设一名User可以有多个Orders,用associasion来实现关联关系

首先数据库表结构

CREATE TABLE `user` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) COLLATE utf8_bin NOT NULL,
  `usernumber` varchar(20) COLLATE utf8_bin NOT NULL,
  `loginname` varchar(20) COLLATE utf8_bin NOT NULL,
  `loginpassword` varchar(20) COLLATE utf8_bin NOT NULL,
  `sex` varchar(4) COLLATE utf8_bin DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
//orders表中为user_id添加外键,指向user表的id
CREATE TABLE `orders` (
  `oid` int(8) NOT NULL AUTO_INCREMENT,
  `orderid` varchar(20) COLLATE utf8_bin NOT NULL,
  `message` varchar(20) COLLATE utf8_bin DEFAULT NULL,
  `user_id` int(8) NOT NULL,
  PRIMARY KEY (`oid`),
  KEY `1001` (`user_id`),
  CONSTRAINT `1001` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Order实体类

        public int oid;
        public String orderid;
        public String message;
        public User user;       //省略get/set方法

Order对象的sql映射文件,order.xml

<mapper namespace="com.mybaits.dao.impl.OrdersImpl">
        <resultMap type="com.mybaits.bean.User" id="userResult">
                <id property="id" column="id" />
                <result property="username" column="username"/>
                <result property="usernumber" column="usernumber"/>
                <result property="loginname" column="loginname"/>
                <result property="loginpassword" column="loginpassword"/>
                <result property="sex" column="sex"/>
                <result property="birthday" column="birthday" />
        </resultMap>

        <resultMap type="com.mybaits.bean.Orders" id="orderResult">
            <id property="oid" column="oid"/>
            <result property="orderid" column="orderid"/>
            <result property="message" column="message"/>        <!--使用resultMap属性引用上面的User实体映射-->
            <association property="user" column="user_id" javaType="com.mybaits.bean.User" jdbcType="INTEGER" resultMap="userResult">
            </association>
        </resultMap>

        <select id="findAllOrders" resultMap="orderResult">
            select * from orders o left join user u on o.user_id=u.id
        </select>

        <insert id="saveOrder" parameterType="Orders">
            insert into orders (orderid,message,user_id) values(#{orderid},#{message},#{user.id})
        </insert>

</mapper>

OrderTest类

@Test
    public void Test2(){
        List<Orders> l=order.findOrders();
        for(int i=0;i<l.size();i++){
            System.out.println(l.get(i));
        }
    }
订单编号:10001    订单信息:订单1    下单用户:BN
订单编号:10002    订单信息:订单2    下单用户:BN
订单编号:10003    订单信息:订单3    下单用户:qwe
订单编号:10004    订单信息:订单4    下单用户:qwe
订单编号:10005    订单信息:订单5    下单用户:JAVA

利用collection在User对象中关联

1.在User中添加 List<Orders> orders 属性

private List<Orders> orders=new ArrayList<Orders>();//get/set方法

2.User的sql映射文件user.xml

     <resultMap type="com.mybaits.bean.User" id="userResult">
                <id property="id" column="id" />
                <result property="username" column="username"/>
                <result property="usernumber" column="usernumber"/>
                <result property="loginname" column="loginname"/>
                <result property="loginpassword" column="loginpassword"/>
                <result property="sex" column="sex"/>
                <result property="birthday" column="birthday" />                 //collection元素映射 user对象中order的集合属性,resultMap指向下面的order的resultMap
                <collection property="orders" ofType="Orders" resultMap="orderResult"></collection>
        </resultMap>
       <resultMap type="com.mybaits.bean.Orders" id="orderResult">
            <id property="oid" column="oid"/>
            <result property="orderid" column="orderid"/>
            <result property="message" column="message"/>
        </resultMap>

      <select id="getUOBN" parameterType="string" resultMap="userResult">
             select * from user u left join orders o on o.user_id=u.id where u.usernumber=#{usernumber}    
          </select>


3.测试类

@Test
    public void Test11(){
        User u=userDao.findUserOrders("01111001");
        System.out.println("用户:"+u.getUsername()+"\n订单总数:"+u.getOrders().size());
        for(Orders o:u.getOrders()){
            System.out.println("订单号:"+o.getOrderid()+"\t订单信息:"+o.getMessage());
        }

    }

用户:BN
订单总数:2
订单号:10001    订单信息:订单1
订单号:10002    订单信息:订单2
时间: 2024-08-04 11:57:16

MyBatis对象关联关系---- association与collection的相关文章

mybatis一对一关联关系映射

mybatis一对一关联关系映射 在关联关系中,有一对一,一对多,多对多三种关联关系. 一对一关系:在操作上,任意一方引入对方的主键作为外键. 一对多关系:在"多"的一方添加"一"的一方的主键作为外键. 多对多关系:产生中间表引入两张表的主键作为外键,将两个主键作为联合主键或者引入新的字段作为这个中间表的主键. 一对一关联关系 例如person和IDcard,一个人只有一个身份证号,而一个身份证号只对应一个人. 以上是person表和IDcard表. public

mybatis-利用association和collection实现一对一和一对多

有关于Association和Collection的探究 场景:一个父亲有多个儿子,一个儿子只有一个父亲(一对多场景) 数据库表结构: father表:fid(int unique),fname(varchar) son表:sid(int unique),sname(varchar),s_fid(int) father表中的fid是主键 son表中的s_fid是father表中fid的外键 pojo: Father类:fid(int),fname(String),slist(List<Son>

mybatis报错Mapped Statements collection does not contain value for com.inter.IOper

首页 > 精品文库 > mybatis报错Mapped Statements collection does not contain value for com.inter.IOper mybatis报错Mapped Statements collection does not contain value for com.inter.IOper 2015-04-09 浏览(52) [摘要:正在顺序挪用IOperation接心中的getAllItems方式时,涌现了以下毛病: Exception

mybatis 使用resultMap实现关联数据的查询(association 和collection )

<?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"> <!-- namespace的名字需要跟接口的类名一致 --> <mapper namesp

mybatis association和collection标签怎么用

<resultMap type="Bill" id="ResultBill"> <id property="id" column="id"/> <result property="dh" column="dh"  /> <result property="rq" column="rq"/> <a

14、mybatis学习——分布查询association或collection中多列值传参 以及 局部方法延迟加载问题

举例注释中说明: <collection property="students" select="com.pxxy.bean.StudentMapper.getStusByColId" column="id" fetchType="lazy"> <!-- 多列值传递时:将多列的值封装成map进行传递 column="{key1=column1,key2=column2}" key为sql语

MyBatis关联查询 (association) 时遇到的某些问题/mybatis映射

先说下问题产生的背景: 最近在做一个用到MyBatis的项目,其中有个业务涉及到关联查询,我是将两个查询分开来写的,即嵌套查询,个人感觉这样更方便重用: 关联的查询使用到了动态sql,在执行查询时就出现了如下错误:Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'id' in 'class java.lang.Integer' 因为出现了这个问题,

MyBatis之关联关系

1.一对一关联 1.1根据班级id查询班级信息,并且查询出老师的信息 1.2 创建表和数据 创建老师表和学生表,假设一个老师只负责一个班级,这样就可以实现一对一关系 CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) ); CREATE TABLE class( c_id INT PRIMARY KEY AUTO_INCREMENT, c_name VARCHAR(20), teacher_i

[04] 高级映射 association和collection

之前我们提到的映射,都是简单的字段和对象属性一对一,假设对象的属性也是一个对象,即涉及到两个表的关联,此时应该如何进行映射处理? 先看两张表,author 和 book:    业务上对应关系为,一个作者能写多本书,但是一本书只有一个作者.对应的Java类如下: public class Book { private long id; private String name; private int price; private Author author; //... getter and s