one2many &&many2many
只记录双向的情况(双向是单向的一种)
@OneToMany 和 @ManyToOne :一个Group 包含多个 User;
Group.class
package com.XX.model; import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "t_group")
public class Group { private String id;
private String name;
private String title;
private Set<User> users; //说明代码一
@Id
@GeneratedValue(generator = "sys-uuid")
@GenericGenerator(name = "sys-uuid", strategy = "uuid2")
public String getId() {
return id;
} public String getName() {
return name;
} public String getTitle() {
return title;
} //说明代码二
@OneToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER, mappedBy = "group")
public Set<User> getUsers() {
return (users==null)? new HashSet<User>():users;
} public void setId(String id) {
this.id = id;
} public void setName(String name) {
this.name = name;
} public void setTitle(String title) {
this.title = title;
} public void setUsers(Set<User> users) {
this.users = users;
} //说明代码三
/* public void addUser(User user) {
if(this.users == null){
this.users = new HashSet<User>();
}
users.add(user);
}*/
}
User.class
package com.XX.model; import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "t_user")
public class User { private String id;
private String name;
private int age;
private Group group; @Id
@GeneratedValue(generator = "sys-uuid")
@GenericGenerator(name = "sys-uuid", strategy = "uuid2")
public String getId() {
return id;
} public String getName() {
return name;
} public int getAge() {
return age;
}
//说明代码二
@ManyToOne(cascade = {CascadeType.ALL})
public Group getGroup() {
return group;
} public void setId(String id) {
this.id = id;
} public void setName(String name) {
this.name = name;
} public void setAge(int age) {
this.age = age;
} public void setGroup(Group group) {
this.group = group;
} }
测试代码:
package com.XX.model; import java.util.Set; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test; public class GroupTest { private static SessionFactory sessionFactory; @BeforeClass
public static void beforeClass(){
//hibernate 5.0.0.Final及之后的写法
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); Metadata metadata = new MetadataSources(registry).getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} @Test
public void test() {
Group group = new Group();
group.setName("group1");
group.setTitle("test"); User user = new User();
user.setName("yuc");
user.setAge(0); Set<User> users = group.getUsers();
users.add(user);
group.setUsers(users);
//说明代码三
//group.addUser(user); Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(group);
session.getTransaction().commit(); //说明代码四
session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.get(Group.class, "1"); } @AfterClass
public static void afterClass(){
sessionFactory.close();
} }
说明代码一:
ID用 String 存储,保存时自动生成,跨数据库(mysql、oracle均实用);
说明代码二:
@manytoone & @onetomany 双向关联时,manytoone 一方用mappedBy 进行关联(否则数据库会出现两个关联关系,重复);
代码说明三:
在多的一方辅助增加一个子元素。不足:破坏bean 的完整性(一般bean层级只有元素和对应的get/set方法);
代码说明四:
用于说明@manytoone 和 @onetomany 的默认加载方式:
@manytoone 默认加载方式是FetchType.LAZY;
@onetomany 默认加载方式是FetchType.EAGER;
运行代码如下:
数据库结果如下:
@manyToMany双向关联 :一个Teacher有多个Student,一个Student有多个Teacher;
Teacher.class
package com.ajs.model; import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "t_teacher")
public class Teacher { private String id;
private String name;
private String title;
private Set<Student> students; @Id
@GeneratedValue(generator = "sys-uuid")
@GenericGenerator(name = "sys-uuid", strategy = "uuid2")
public String getId() {
return id;
} //说明代码五
@ManyToMany(targetEntity=Student.class, fetch = FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy = "teachers")
public Set<Student> getStudents() {
return students;
} public void setStudents(Set<Student> students) {
this.students = students;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
}
}
Student.class
测试代码
@Test
public void test() {
Teacher teacher = new Teacher();
teacher.setName("tea1");
teacher.setTitle("test"); Student student = new Student();
student.setName("yuc");
student.setAge(20); Set<Student> students= new HashSet<Student>();
students.add(student);
teacher.setStudents(students);
Set<Teacher> teachers= new HashSet<Teacher>();
teachers.add(teacher);
student.setTeachers(teachers); Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(teacher);
session.getTransaction().commit(); session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.get(Student.class, "1");
}
说明代码五:
package com.ajs.model; import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "t_student")
public class Student { private String id;
private String name;
private int age;
private Set<Teacher> teachers; @Id
@GeneratedValue(generator = "sys-uuid")
@GenericGenerator(name = "sys-uuid", strategy = "uuid2")
public String getId() {
return id;
} public String getName() {
return name;
} public int getAge() {
return age;
} //说明代码五
@ManyToMany(targetEntity=Teacher.class, fetch = FetchType.EAGER, cascade={CascadeType.ALL})
@JoinTable(name="t_teacher_student",
joinColumns=@JoinColumn(name="student_id"),
inverseJoinColumns=@JoinColumn(name="teacher_id"))
public Set<Teacher> getTeachers() {
return teachers;
} public void setId(String id) {
this.id = id;
} public void setName(String name) {
this.name = name;
} public void setAge(int age) {
this.age = age;
} public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
}
双向一样用 mappedBy 对其中一方进行限制,fetch = FetchType.EAGER手动将加载方式改为急加载,需要用targetEntity指定对应的关联类是哪一个;
@JoinTable(name="t_teacher_student", joinColumns=@JoinColumn(name="student_id"),inverseJoinColumns=@JoinColumn(name="teacher_id"))
@JoinTable可以自定义对应的中间表名字,当前实体对象关联的中间表字段名称,已经中间表关联另一方的对应名称;
运行代码如下:
数据库结果如下:
one2many &&many2many的更多相关文章
- Mybatis对象关系映射 one2one,one2many,many2many
MyBatis中的高级映射一般要借助select元素中的resultMap属性进行实现,通过此属性配置实现一对一,一对多等关系映射的实现 一对一映射:association 一对多映射:collect ...
- OpenERP 的XML-RPC的轻度体验+many2many,one2many,many2one创建方式
来自:http://cn.openerp.cn/openerp_import_image_by_xmlrpc/ 每当夏秋之交,我们都有展会,展会完后,都有很多的新的潜在客户要添加,我们收了一大堆名片, ...
- laravel model relationship
laravel支持多种模型之间的relation,对应着模型间的one2one, one2many,many2many,hasManyThrough,Polymorphic, many2many po ...
- 7、ORM
CRUD(create.retrieve.update.delete) left join right join inner join one2one one2many many2many 1.For ...
- odoo domain详解
参考的以下文档: luohuayong:Odoo domain写法及运用 baimo:odoo domain表达式 1.domain 表达式规则 最简单的格式:[('字段名','操作符',值)] 例: ...
- Odoo中的Widget
转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826144.html 一:Widget是什么 Odoo中定义了字段的显示形式,不同字段类型的字段都有其不同 ...
- openerp many2many
many2many (0,0,{values}) 根据values里面的信息新建一个记录. (1,ID,{values})更新id=ID的记录(写入values里面的数据) (2,ID) 删除id=I ...
- Odoo Many2many 指定默认分组过滤
在odoo里如果想单击某个菜单打开的页面是自带过滤的,可以在打开菜单的动作中添加默认过滤来实现,今天有同学在群里问,如何在Many2many的添加更多的弹出窗口中添加类似的过滤,其实是非常非常简单的, ...
- 在xml中对one2many 字段屏蔽 添加项目
在xml中对one2many 字段(mrp_workorder_variation_line_ids) 设置 只有在草稿状态下才能编辑 <field name="mrp_workord ...
随机推荐
- ios 第2天
类的方法和实例的方法 -(void)runwithspeed:(int)speed and direction:(int)direction; 实例方法 -开头 运用对象调用 函数名为runwiths ...
- ES6入门之对象扩展
ES5对象(超类)原有: 属性:construct构造函数 方法: object.hasOwnProperty( propertyName ) //检测是否有一个本地的属性而不是继承的,返回boole ...
- windows下gvim搭建IDE
原文转载自:手把手教你把Vim改装成一个IDE编程环境(图文) 如侵犯您的版权,请联系:windeal12@qq.com By: 吴垠 Date: 2007-09-07 Version: 0.5 Em ...
- oracle和sql server 比较
Oracle SQLServer 比较 字符数据类型 CHAR CHAR 都是固定长度字符资料但oracle里面最大度为2kb,SQLServer里面最大长度为8kb 变长字符数据类型 ...
- Gradle 1.12用户指南翻译——第六十五章. Maven 发布(新)
其他章节的翻译请参见:http://blog.csdn.net/column/details/gradle-translation.html翻译项目请关注Github上的地址:https://gith ...
- Android 开发技术选型(博客,新闻,阅读类)
前言 最开始学习写应用的时候,发现类聚合数据这个平台可以提供一些免费数据接口,于是写了个人的第一个应用-– JuheNews,当时的知识储备稍显粗糙,虽然现在的知识也不咋滴,但是相对之前而言还是有些进 ...
- Compass入门
一.Compass是什么? 简单说,Compass是Sass的工具库(toolkit). Sass本身只是一个编译器,Compass在它的基础上,封装了一系列有用的模块和模板,补充Sass的功能. ...
- fedora 26 Mysql
安装 Fedora用dnf默认安装的使Mariadb,即 [*****@localhost ~]$ sudo dnf install mysql-server ... [*****@localhost ...
- Codeforces 914H Ember and Storm's Tree Game 【DP】*
Codeforces 914H Ember and Storm's Tree Game 题目链接 ORZ佬 果然出了一套自闭题 这题让你算出第一个人有必胜策略的方案数 然后我们就发现必胜的条件就是树上 ...
- XML 的 XPath 语法
XPath 是 XML 路径语言(XML Path Language),用来确定XML文档中某部分位置的语言.无论是什么语言什么框架,几乎都可以使用 XPath 来高效查询 XML 文件. 本文将介绍 ...