Hibernate的多种关系映射(oto、otm、mtm)
前提:使用注解映射
一、一对一(夫妻关系表)
两个表:hus1和wife1表,外键为id,各自有名字hname和wname
映射得到两个类:Hus1和Wife1类
Hus1类(主表):
package com.weikun.po; import javax.persistence.*; /**
* Created by Administrator on 2018/3/26.
*/
@Entity
public class Hus1 {
private int id;
private String hname;
private Wife1 wife; @Id
@Column(name = "id", nullable = false)
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Basic
@Column(name = "hname", nullable = true, length = 10)
public String getHname() {
return hname;
} public void setHname(String hname) {
this.hname = hname;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Hus1 hus1 = (Hus1) o; if (id != hus1.id) return false;
if (hname != null ? !hname.equals(hus1.hname) : hus1.hname != null) return false; return true;
} @Override
public int hashCode() {
int result = id;
result = 31 * result + (hname != null ? hname.hashCode() : 0);
return result;
} @OneToOne(cascade ={CascadeType.ALL})
@JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
public Wife1 getWife() {
return wife;
} public void setWife(Wife1 wife) {
this.wife = wife;
}
}
Wife1类
package com.weikun.po; import javax.persistence.*; /**
* Created by Administrator on 2018/3/26.
*/
@Entity
public class Wife1 {
private int id;
private String wname;
private Hus1 hus1ById;
private Hus1 hus; @Id
@Column(name = "id", nullable = false)
public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} @Basic
@Column(name = "wname", nullable = true, length = 10)
public String getWname() {
return wname;
} public void setWname(String wname) {
this.wname = wname;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Wife1 wife1 = (Wife1) o; if (id != wife1.id) return false;
if (wname != null ? !wname.equals(wife1.wname) : wife1.wname != null) return false; return true;
} @Override
public int hashCode() {
int result = id;
result = 31 * result + (wname != null ? wname.hashCode() : 0);
return result;
} @OneToOne
@JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
public Hus1 getHus1ById() {
return hus1ById;
} public void setHus1ById(Hus1 hus1ById) {
this.hus1ById = hus1ById;
} @OneToOne(mappedBy = "wife")
public Hus1 getHus() {
return hus;
} public void setHus(Hus1 hus) {
this.hus = hus;
}
}
对两个表进行操作:
package com.weikun.dao; import com.weikun.po.Hus1;
import com.weikun.po.Wife1;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test; /**
* Created by Administrator on 2018/3/26.
*/
public class HusDAOImpl {
private SessionFactory sf=null;
private Configuration configuration=null;
public HusDAOImpl(){
configuration=new Configuration().configure("hibernate.cfg.xml");
sf=configuration.buildSessionFactory();
}
@Test
public void update(){
Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try{
Hus1 hus=session.load(Hus1.class,6);
hus.setHname("C");
hus.getWife().setWname("PS");
session.update(hus); trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
}
session.close();
}
@Test
public void del(){ Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try{
Hus1 hus=session.load(Hus1.class,1); session.delete(hus); trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
}
session.close();
}
@Test
public void add(){
Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try{
Hus1 hus=new Hus1();
hus.setHname("JAVA");
hus.setId(6); Wife1 wif=new Wife1();
wif.setWname("python");
wif.setId(6);
hus.setWife(wif); wif.setHus(hus); session.save(hus); trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
}
session.close(); }
@Test
public void queryById(){
Session session=sf.openSession();
Hus1 hus=session.load(Hus1.class,1);//
System.out.printf("%s-%s",hus.getHname(),hus.getWife().getWname());
Wife1 wife=session.load(Wife1.class,1);//
System.out.printf("%s-%s",wife.getWname(),wife.getHus().getHname());
session.close();
}
}
二、一对多(父子关系表)
两个表:父亲表(father2)、儿子表(son2),外键为fid,父亲表中属性有fid、fname,儿子表中有属性sid、sname、fid
映射得到两个类:Father2和Son2类
Father2类:
package com.weikun.po; import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import javax.persistence.*;
import java.util.HashSet;
import java.util.Set; /**
* Created by Administrator on 2018/3/26.
*/
@Entity
public class Father2 {
private int fid;
private String fname;
private Set<Son2> sons=new HashSet<Son2>(); @Id
@Column(name = "fid", nullable = false)
public int getFid() {
return fid;
} public void setFid(int fid) {
this.fid = fid;
} @Basic
@Column(name = "fname", nullable = true, length = 10)
public String getFname() {
return fname;
} public void setFname(String fname) {
this.fname = fname;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Father2 father2 = (Father2) o; if (fid != father2.fid) return false;
if (fname != null ? !fname.equals(father2.fname) : father2.fname != null) return false; return true;
} @Override
public int hashCode() {
int result = fid;
result = 31 * result + (fname != null ? fname.hashCode() : 0);
return result;
} @OneToMany(mappedBy = "father",cascade = {CascadeType.ALL})
//@Fetch(FetchMode.JOIN)
public Set<Son2> getSons() {
return sons;
} public void setSons(Set<Son2> sons) {
this.sons = sons;
}
}
Son2类:
package com.weikun.po; import javax.persistence.*; /**
* Created by Administrator on 2018/3/26.
*/
@Entity
public class Son2 {
private int sid;
private String sname;
private Father2 father2ByFid;
private Father2 father2ByFid_0;
private Father2 father; @Id
@Column(name = "sid", nullable = false)
public int getSid() {
return sid;
} public void setSid(int sid) {
this.sid = sid;
} @Basic
@Column(name = "sname", nullable = true, length = 10)
public String getSname() {
return sname;
} public void setSname(String sname) {
this.sname = sname;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Son2 son2 = (Son2) o; if (sid != son2.sid) return false;
if (sname != null ? !sname.equals(son2.sname) : son2.sname != null) return false; return true;
} @Override
public int hashCode() {
int result = sid;
result = 31 * result + (sname != null ? sname.hashCode() : 0);
return result;
} @ManyToOne
@JoinColumn(name = "fid", referencedColumnName = "fid")
public Father2 getFather() {
return father;
} public void setFather(Father2 father) {
this.father = father;
}
}
操作父子关系:
package com.weikun.dao; import com.weikun.po.Father2;
import com.weikun.po.Son2;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.junit.Test; import javax.persistence.Table;
import java.util.List; /**
* Created by Administrator on 2018/3/26.
*/
public class FatherDAOImpl {
private SessionFactory sf=null;
private Configuration configuration=null;
public FatherDAOImpl(){
configuration=new Configuration().configure("hibernate.cfg.xml");
sf=configuration.buildSessionFactory();
}
@Test
public void del(){
Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try {
//Son2 s=session.load(Son2.class,6);
Father2 s=session.load(Father2.class,6);
session.delete(s);
trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
} session.close(); } public static void main(String[] args) { }
@Test
public void go(){
Father2 s=query();
s.getSons().forEach(s1->System.out.println(s1.getSname()));
}
public Father2 query(){
Session session=sf.openSession();
Father2 s=null;
try {
//Son2 s=session.load(Son2.class,6);
s=session.get(Father2.class,6);
if(!Hibernate.isInitialized(s.getSons())){//lazy的必须解决方案,访问子表情况
Hibernate.initialize(s.getSons());
}
//s.getSons().forEach(s1->System.out.println(s1.getSname())); }catch(Exception e){ e.printStackTrace();
} session.close();
return s;
}
@Test
public void query2(){
Session session=sf.openSession();
Father2 s=null;
try {
//Son2 s=session.load(Son2.class,6);
Query q=session.createQuery("from Father2 as a ");
q.setLockMode("a", LockMode.UPGRADE_NOWAIT);//强力锁止
q.setCacheable(true);
q.list(); Query q2 =session.createQuery("from Father2 where fid=1");
q2.setCacheable(true);
q2.list(); }catch(Exception e){ e.printStackTrace();
} session.close(); }
@Test
public void query1(){
Session session=sf.openSession(); try {
Son2 s=session.load(Son2.class,6); System.out.println(s.getFather().getFname()); }catch(Exception e){ e.printStackTrace();
} session.close();
}
@Test
public void add(){
Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try {
Father2 f=new Father2();
f.setFid(6);
f.setFname("JASON"); Son2 s=new Son2();
s.setSid(6);
s.setSname("ROSE");
s.setFather(f); Son2 s1=new Son2();
s1.setSid(7);
s1.setSname("MARY");
s1.setFather(f);
f.getSons().add(s);
f.getSons().add(s1);
session.save(f);
trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
} session.close();
}
}
三、多对多(老师学生关系)
三个表只映射两个,tea、stu,而管理两个表关系的teastu表不用映射导入
映射tea和stu表得到Stu类和Tea类
Tea类:
package com.weikun.po; import org.hibernate.annotations.Cascade; import javax.persistence.*;
import java.util.HashSet;
import java.util.Set; /**
* Created by Administrator on 2018/3/26.
*/
@Entity
public class Tea {
private int tid;
private String tname;
private Set<Stu> stus=new HashSet<>(); @Id
@Column(name = "tid", nullable = false)
public int getTid() {
return tid;
} public void setTid(int tid) {
this.tid = tid;
} @Basic
@Column(name = "tname", nullable = true, length = 10)
public String getTname() {
return tname;
} public void setTname(String tname) {
this.tname = tname;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Tea tea = (Tea) o; if (tid != tea.tid) return false;
if (tname != null ? !tname.equals(tea.tname) : tea.tname != null) return false; return true;
} @Override
public int hashCode() {
int result = tid;
result = 31 * result + (tname != null ? tname.hashCode() : 0);
return result;
}
@Cascade(value=org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@ManyToMany()
@JoinTable(name = "teastu", catalog = "res", schema = "res", joinColumns = @JoinColumn(name = "tid", referencedColumnName = "tid", nullable = false), inverseJoinColumns = @JoinColumn(name = "sid", referencedColumnName = "sid", nullable = false))
public Set<Stu> getStus() {
return stus;
} public void setStus(Set<Stu> stus) {
this.stus = stus;
}
}
Stu类:
package com.weikun.po; import javax.persistence.*;
import java.util.HashSet;
import java.util.Set; /**
* Created by Administrator on 2018/3/26.
*/
@Entity
public class Stu {
private int sid;
private String sname;
private Set<Tea> teas=new HashSet<>(); @Id
@Column(name = "sid", nullable = false)
public int getSid() {
return sid;
} public void setSid(int sid) {
this.sid = sid;
} @Basic
@Column(name = "sname", nullable = true, length = 10)
public String getSname() {
return sname;
} public void setSname(String sname) {
this.sname = sname;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Stu stu = (Stu) o; if (sid != stu.sid) return false;
if (sname != null ? !sname.equals(stu.sname) : stu.sname != null) return false; return true;
} @Override
public int hashCode() {
int result = sid;
result = 31 * result + (sname != null ? sname.hashCode() : 0);
return result;
} @ManyToMany(mappedBy = "stus")
public Set<Tea> getTeas() {
return teas;
} public void setTeas(Set<Tea> teas) {
this.teas = teas;
}
}
操纵师生关系的类:
package com.weikun.dao; import com.weikun.po.Father2;
import com.weikun.po.Stu;
import com.weikun.po.Tea;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test; /**
* Created by Administrator on 2018/3/26.
*/
public class TeaDAOImpl {
private SessionFactory sf=null;
private Configuration configuration=null;
public TeaDAOImpl(){
configuration=new Configuration().configure("hibernate.cfg.xml");
sf=configuration.buildSessionFactory();
}
@Test
public void del(){
Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try {
Tea t=session.load(Tea.class,6);
session.delete(t);
trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
} session.close(); }
@Test
public void add(){
Session session=sf.openSession();
Transaction trans=session.beginTransaction();
try {
Tea t=new Tea();
t.setTid(6);
t.setTname("MARY"); Tea t1=new Tea();
t1.setTid(7);
t1.setTname("NICK"); Stu s1=new Stu();
s1.setSid(10);
s1.setSname("S1");
s1.getTeas().add(t);
s1.getTeas().add(t1); Stu s2=new Stu();
s2.setSid(11);
s2.setSname("S2");
s2.getTeas().add(t);
s2.getTeas().add(t1);
t1.getStus().add(s1);
t1.getStus().add(s2);
t.getStus().add(s1);
t.getStus().add(s2); session.save(t);
session.save(t1);
trans.commit();
}catch(Exception e){
trans.rollback();
e.printStackTrace();
} session.close();
} }
Hibernate的多种关系映射(oto、otm、mtm)的更多相关文章
- Hibernate多对多关系映射(建表)
下边讲述Hibernate多对多关系映射. 多对多关系的表的结构为: 两个实体表,还包含一个关系表,关系表为复合主键,如果要使用Hibernate多对多关系映射,则关系表必须只包含两个字段,如果生成了 ...
- 菜鸟学习Hibernate——多对多关系映射
Hibernate中的关系映射,最常见的关系映射之一就是多对多关系映射例如用户与角色的关系,一个用户对应多个角色,一个角色对应多个用户.如图: Hibernate中如何来映射这两个的关系呢? 下面就为 ...
- 菜鸟学习Hibernate——一对多关系映射
Hibernate中的关系映射,最常见的关系映射之一就是一对多关系映射例如学生与班级的关系,一个班级对应多个学生.如图: Hibernate中如何来映射这两个的关系呢? 下面就为大家讲解一下: 1.创 ...
- hibernate的对象/关系映射结果为空,exists查不到值的问题-20190823
1: hibernate的对象/关系映射 情景:在使用@onetotone/@manytonone时关联结果为空 原因:在使用这个注解的时候,默认的时crossjoin(交叉连接),在进行查询时以及排 ...
- Hibernate多对多关系映射
两张表的多对多关系,在数据库中通常是通过第三张中间表来实现的,第三张中间表放的是两张表各自的主键值,通过主键与主键的对应来体现表直接的关系.比如在权限系统中,一个用户可以拥有多种权限,而一种权限也可以 ...
- Hibernate学习之关系映射(转)
一.一对多 "一对多"是最普遍的映射关系,简单来讲就如消费者与订单的关系.一对多:从消费者角的度来说一个消费者可以有多个订单,即为一对多.多对一:从订单的角度来说多个订单可以对应一 ...
- Hibernate 中对象关系映射(ObjectRelationMapping)
1.什么是对象关系映射? 解析:对象-关系映射(Object Relational Mapping,简称ORM,对象关系映射)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说, ...
- Hibernate之实体关系映射
延迟加载与即时加载 例如Person类和Email类是一对多关系,如果设为即时加载,当加载Person时,会自动加载Email,如果设置为延迟加载,当第一次调用person.getEmails()时才 ...
- Hibernate:对象关系映射(一对一,一对多,多对一,多对多)
如需转载,请说明出处:http://www.cnblogs.com/gudu1/p/6895610.html Hibernate通过关系映射来表示数据库中表与表之间的关系,关系映射可以通过两种方式:配 ...
随机推荐
- Android开发之配置adb工具的环境变量
在Android开发中,adb是一个非常好用也非常使用的工具,可是使用的时候假设没有改动环境变量,每一次都须要输入全然路径非常麻烦.解决的方法是在环境变量中加入adb工具的路径. Windows平台 ...
- 初探swift语言的学习笔记十(block)
作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35783341 转载请注明出处 假设觉得文章对你有所帮助,请通过留言 ...
- [Android 性能优化系列]内存之基础篇--Android怎样管理内存
大家假设喜欢我的博客,请关注一下我的微博,请点击这里(http://weibo.com/kifile),谢谢 转载请标明出处(http://blog.csdn.net/kifile),再次感谢 原文地 ...
- apiCloud中的数据库操作mcm-js-sdk的使用
1.引入js <!-- 引入mcm-js-sdk Begin --> <script type="text/javascript" src="../pl ...
- Oracle的awr和ash
1. 10g之前 用户的连接将产生会话,当前会话记录保存在v$session中:处于等待状态的会话会被复制一份放在v$session_wait中.当该连接断开后,其原来的连接信息在v$sess ...
- 如何让NSURLConnection在子线程中运行
可以有两个办法让NSURLConnection在子线程中运行,即将NSURLConnection加入到run loop或者NSOperationQueue中去运行. 前面提到可以将NSTimer手动加 ...
- js 转化为几天前,几小时前,几分钟前...
转换标准时间为时间戳: function getDateTimeStamp(dateStr){ return Date.parse(dateStr.replace(/-/gi,"/" ...
- c++ set_union set_intersection使用
自定义类型也可以构造set,但同样必须定义“小于”运算符,set中的元素从小到大排列好了 #include<iostream>#include<string>#include ...
- docker初安装的血泪史
最近docker很火,不管是朋友圈内还是公司内聊天都离不开docker,于是对docker产生了极大的好奇心,凭着一颗程序猿的好奇心开始了docker的安装血泪史. 首先我有一台从公司退役的本本x22 ...
- Spark RDD概念学习系列之transformation操作
不多说,直接上干货! transformation操作 惰性求值 (1)RDD 的转化操作都是惰性求值的.这意味着在被调用行动操作之前Spark不会开始计算. (2)读取数据到RDD的操作也是惰性的. ...