Mybatis中collection和association的使用区别

您所在的位置:网站首页 球衣icon和association有啥区别啊 Mybatis中collection和association的使用区别

Mybatis中collection和association的使用区别

2024-04-24 10:52| 来源: 网络整理| 查看: 265

1. 关联-association2. 集合-collection

比如同时有User.java和Card.java两个类

User.java如下:

public class User{

private Card card_one;

private List card_many;

}

在映射card_one属性时用association标签, 映射card_many时用collection标签.

所以association是用于一对一和多对一,而collection是用于一对多的关系

下面就用一些例子解释下吧

association-一对一

人和身份证的关系

下面是pojo

  1 2 3 4 5 public class Card implements Serializable{ private Integer id; private String code; //省略set和get方法. }

 

  1 2 3 4 5 6 7 8 9 public class Person implements Serializable{ private Integer id; private String name; private String sex; private Integer age; //人和身份证是一对一的关系 private Card card; //省略set/get方法. }

下面是mapper和实现的接口

  1 2 3 4 5 6 7 package com.glj.mapper;   import com.glj.poji.Card;   public interface CardMapper { Card selectCardById(Integer id); }

 

  1 2 3 4 5 6 7 8 9 select * from tb_card where id = #{id}

 

  1 2 3 4 5 6 7 package com.glj.mapper;   import com.glj.poji.Person;   public interface PersonMapper { Person selectPersonById(Integer id); }

 

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 select * from tb_person where id = #{id}

PersonMapper.xml 还使用association的分步查询。

同理多对一,也是一样

只要那个pojo出现private Card card_one;

即使用association

collection 一对多和association的多对一关系

学生和班级的一对多的例子

pojo类

  1 2 3 4 5 6 7 8 9 10 11 12 13 package com.glj.pojo;   import java.io.Serializable; import java.util.List;   public class Clazz implements Serializable{ private Integer id; private String code; private String name;         //班级与学生是一对多的关系 private List students; //省略set/get方法 }

 

  1 2 3 4 5 6 7 8 9 10 11 12 13 package com.glj.pojo;   import java.io.Serializable;   public class Student implements Serializable { private Integer id; private String name; private String sex; private Integer age;         //学生与班级是多对一的关系 private Clazz clazz; //省略set/get方法 }

 

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 select * from tb_clazz where id = #{id}

 

  1 2 3 4 5 6 7 package com.glj.mapper;   import com.glj.pojo.Clazz;   public interface ClazzMapper { Clazz selectClazzById(Integer id); }

ClazzMapper使用到了集合-collection 即为一对多,一个班级面对多个学生

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 select * from tb_clazz c,tb_student s where c.id = s.id and s.id = #{id} select * from tb_student where clazz_id = #{id}

 

  1 2 3 4 5 6 7 package com.glj.mapper;   import com.glj.pojo.Student;   public interface StudentMapper { Student selectStudentById(Integer id); }

StudentMapper则是与班级为多对一关系,所以使用了关联-association

嗯,希望我以后又不记得二者的关系时,能感谢现在总结的自己

附上一张mybatis的类型别名图



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3