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;

Orders实体类

        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"/>
        
<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><!--使用resultMap属性引用上面的User实体映射-->

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

http://www.voidcn.com/blog/fqf_520/article/p-4973660.html

I am going to assume that you have a many to many relationship between Projects and Employees, which is why you created a Project Assignment table. This Project Assignment table / object may only have two fields/columns: a mapping of project id to employee id - a classic "bridge table" (aka "join" or "junction" table).

When you map this model to an object graph, you have three options:

A Project object can have a list of all employees assigned to it
An Employee object can have a list of projects s/he is assigned to
Create a Project Assignment object that has a mapping of each projects to its employee and each employee to his/her project.
In your example you chose the last option.

Association

An association is a single mapping for a "has-one" relationship.

Suppose an Employee can only be assigned to one Project at a time. Some models call this a "has-one" or "belongs to" relationship. If you want to make Employee your "primary" focus in the object graph, then you would map it with an association to his/her Project:

<resultMap id="employeeResultMap" type="Employee">
<constructor>
<idArg column="employee_id" javaType="_integer"/>
</constructor>
<result property="firstName" column="first_name"/>
<result property="lastName" column="last_name"/>
<!-- etc. for other simple properties of Employee -->

<!-- Project is a "complex property" of Employee, so we use an -->
<!-- association to grab all of the Projects properties also -->
<association property="assignedProject" resultMap="projectResultMap"/>
</resultMap>
In this case your objects would look like this:

public Employee {
int id;
String firstName;
String lastName
Project assignedProject;
}

public Project {
int id;
String name;
String abc;
}

Collection

An collection is a "list" or "set" of associations.

Now model the inverse - we make Project the primary focus. A Project has a "has-many" relationship with Employee, so it will have a list or collection of those, so we use a "collection" mapping:

<resultMap id="projectResultMap" type="Project">
<constructor>
<idArg column="project_id" javaType="_integer"/>
<arg column="name" javaType="String"/>
</constructor>
<result property="abc" column="abc"/>

<!-- This tells mybatis that there can be multiple Employees -->
<!-- to look up and get their properties -->
<collection property="employees" ofType="Employee">
<constructor>
<idArg column="employee_id" javaType="_integer"/>
</constructor>
<result property="firstName" column="first_name"/>
<result property="lastName" column="last_name"/>
</collection>
</resultMap>
Now your objects would look like this:

public Employee {
int id;
String firstName;
String lastName
}

public Project {
int id;
String name;
String abc;
List<Employee> employees;
}

Project Association

To have a Project Association object, you would either need:

A single Project Association object that maps all projects to employees and vice versa
One Project Association object per project, mapping a project to its employees
One Project Association object per employee, mapping an employee to his/her projects
The first option is rather complex and messy - you would be trying to do relational mapping with object graphs (hash tables most likely).

I would choose to make one of the entities (Project or Employee) the primary focus and then model it as I showed above. The one case I didn't cover is if Employee is your primary focus and an Employee can be on multiple projects, then make that a "has-many" relationship using a collection rather than the association I used above.

Final Note: if it would help to see examples of using a "has-one" association and a "has-many" collection, see the MyBatis Koans I created: https://github.com/midpeter444/mybatis-koans. Koans 10 and 11 demonstrate this.

http://stackoverflow.com/questions/12425384/difference-between-collection-and-association-mapping-in-mybatis-3
http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html

https://github.com/ShawnyXiao/SpringBoot-MyBatis
https://github.com/oneone1995/M-Volunteer-SpringBoot

待确定:
https://github.com/sunlightcs/renren-security

difference between collection and association mapping in mybatis 3的更多相关文章

  1. Mybatis中的collection、association来处理结果映射

    前不久的项目时间紧张,为了尽快完成原型开发,写了一段效率相当低的代码. 最近几天闲下来,主动把之前的代码优化了一下:)   标签:Java.Mybatis.MySQL 概况:本地系统从另外一个系统得到 ...

  2. Mybatis之collection与association标签

    collection与association标签的功能就是为了解决查询条件映射到一个类或一个集合上,适用于对于多对一,一对多的映射结果,现在我们就探究其具体使用吧. 环境搭建: 数据库搭建 CREAT ...

  3. 今天第一天开通博客,随笔总结一下resultType(属性)和resultMap,collection和association,Statement和PreparedStatement各自的区别

    1.resultType(属性)和resultMap(标签引用)的区别? resultType不支持自定义返回结果,会将查询到的结果通过到type中java对象的同名的属性,对象中的属性名必须和数据库 ...

  4. mybatis 一对一与一对多collection和association的使用

    在mybatis如何进行一对一.一对多的多表查询呢?这里用一个简单的例子说明. 一.一对一 1.association association通常用来映射一对一的关系,例如,有个类user,对应的实体 ...

  5. mybatis中collection和association的作用以及用法

    deptDaoMapper.xml 部门对应员工(1对多的关系) <resultMap type="com.hw.entity.Dept" id="deptinfo ...

  6. Mybatis中collection和association的使用区别

    1. 关联-association2. 集合-collection 比如同时有User.java和Card.java两个类 User.java如下: public class User{ privat ...

  7. 【转】mybatis 一对一与一对多collection和association的使用

    转自:https://www.cnblogs.com/yansum/p/5819973.html (有修改和补充,红色字体部分)   在mybatis如何进行一对一.一对多的多表查询呢?这里用一个简单 ...

  8. Mybatis中的collection和association一关系

    collection 一对多和association的多对一关系 学生和班级的一对多的例子 班级类: package com.glj.pojo; import java.io.Serializable ...

  9. Mybatis中 collection 和 association 的区别

    public class A{ private B b1; private List<B> b2;} 在映射b1属性时用association标签,(一对一的关系) 映射b2时用colle ...

随机推荐

  1. S3c2440A WINCE平台HIVE注册表+binfs的实现

    今天最大的收获莫过于把binfs和hive注册表同时在三星的平台上实现了,这可是前无古人啊(只是看到好多哥们说找不到三星的HIVE资料),哈哈哈.怕今天的成果日后成炮灰,还是写下来比较好,要养成这样的 ...

  2. Linux - 主机的细部权限规划:ACL 的使用

    ACL 是 Access Control List 的缩写,主要的目的是在提供传统的 owner,group,others 的 read,write,execute 权限之外的细部权限配置.ACL 可 ...

  3. C语言在linux内核中do while(0)妙用之法

    为什么说do while(0) 妙?因为它的确就是妙,而且在linux内核中实现是相当的妙,我们来看看内核中的相关代码: #define db_error(fmt, ...) \ do { \ fpr ...

  4. Android绘图机制(四)——使用HelloCharts开源框架搭建一系列炫酷图表,柱形图,折线图,饼状图和动画特效,抽丝剥茧带你认识图表之美

    Android绘图机制(四)--使用HelloCharts开源框架搭建一系列炫酷图表,柱形图,折线图,饼状图和动画特效,抽丝剥茧带你认识图表之美 这里为什么不继续把自定义View写下去呢,因为最近项目 ...

  5. SharePoint 入门级介绍

    前言:接触SharePoint两年有余,从一开始的小白,变成现在的菜鸟,一路走来,学到很多,现在,想把自己知道的东西,写给大家,尤其是刚刚接触SharePoint的人们,做一个简单的参考.从一开始接触 ...

  6. Nginx安装Nginx-echo模块

    Nginx-echo可以在Nginx中用来输出一些信息,是在测试排错过程中一个比较好的工具.它也可以做到把来自不同链接地址的信息进行一个汇总输出.总之能用起来可以给开发人员带来挺大帮助的.下面看看我们 ...

  7. package.json字段全解

    原文:http://blog.csdn.net/woxueliuyun/article/details/39294375 Name 必须字段. 小提示: 不要在name中包含js, node字样: 这 ...

  8. mysql6.5 操作日志

    创建用户并授权 grant all privileges on database.* to user@localhost identified by '123456'; flush privilege ...

  9. 初识java——java的基础语法

    标识符:计算机语言中各种符号表示某个特定含义的符号. 表示符的命名规则:1,不能用关键字或者true,false,null; 2,标识符可以包含数字,字母,下划线,美元符号. 3,标识符的首字符必须是 ...

  10. IT小团队的管理者的突围之道

    笔者前几天被问到一个问题,你在团队管理方面有什么值得分享的吗?咋一听,实用千言万语,但是事后回忆说出来的东西感觉空无一物,缺少干货.故想通过写一篇随笔思考整理一下,刷新一下自己对小团队管理的认知.这里 ...