前提:使用注解映射

一、一对一(夫妻关系表)

  两个表: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)的更多相关文章

  1. Hibernate多对多关系映射(建表)

    下边讲述Hibernate多对多关系映射. 多对多关系的表的结构为: 两个实体表,还包含一个关系表,关系表为复合主键,如果要使用Hibernate多对多关系映射,则关系表必须只包含两个字段,如果生成了 ...

  2. 菜鸟学习Hibernate——多对多关系映射

    Hibernate中的关系映射,最常见的关系映射之一就是多对多关系映射例如用户与角色的关系,一个用户对应多个角色,一个角色对应多个用户.如图: Hibernate中如何来映射这两个的关系呢? 下面就为 ...

  3. 菜鸟学习Hibernate——一对多关系映射

    Hibernate中的关系映射,最常见的关系映射之一就是一对多关系映射例如学生与班级的关系,一个班级对应多个学生.如图: Hibernate中如何来映射这两个的关系呢? 下面就为大家讲解一下: 1.创 ...

  4. hibernate的对象/关系映射结果为空,exists查不到值的问题-20190823

    1: hibernate的对象/关系映射 情景:在使用@onetotone/@manytonone时关联结果为空 原因:在使用这个注解的时候,默认的时crossjoin(交叉连接),在进行查询时以及排 ...

  5. Hibernate多对多关系映射

    两张表的多对多关系,在数据库中通常是通过第三张中间表来实现的,第三张中间表放的是两张表各自的主键值,通过主键与主键的对应来体现表直接的关系.比如在权限系统中,一个用户可以拥有多种权限,而一种权限也可以 ...

  6. Hibernate学习之关系映射(转)

    一.一对多 "一对多"是最普遍的映射关系,简单来讲就如消费者与订单的关系.一对多:从消费者角的度来说一个消费者可以有多个订单,即为一对多.多对一:从订单的角度来说多个订单可以对应一 ...

  7. Hibernate 中对象关系映射(ObjectRelationMapping)

    1.什么是对象关系映射? 解析:对象-关系映射(Object Relational Mapping,简称ORM,对象关系映射)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说, ...

  8. Hibernate之实体关系映射

    延迟加载与即时加载 例如Person类和Email类是一对多关系,如果设为即时加载,当加载Person时,会自动加载Email,如果设置为延迟加载,当第一次调用person.getEmails()时才 ...

  9. Hibernate:对象关系映射(一对一,一对多,多对一,多对多)

    如需转载,请说明出处:http://www.cnblogs.com/gudu1/p/6895610.html Hibernate通过关系映射来表示数据库中表与表之间的关系,关系映射可以通过两种方式:配 ...

随机推荐

  1. 1003. 我要通过!(20) (ZJUPAT 模拟)

    题目链接:http://pat.zju.edu.cn/contests/pat-b-practise/1003 "答案正确"是自己主动判题系统给出的最令人欢喜的回复.本题属于PAT ...

  2. WebGL 权威资源站小聚

    WebGL 权威资源站小聚 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句 ...

  3. kettle 使用excel模板导出数据

    通过excel进行高速开发报表: 建设思路: 1.首先制订相关的execl模板. 2.通过etl工具(kettle)能够高速的 将数据库中的数据按excel模板导出成新的excel就可以. 当中ket ...

  4. iOS_6_ToolBar+xib+红楼梦

    终于效果图 BeyondViewController.h // // BeyondViewController.h // 6_ToolBar // // Created by beyond on 14 ...

  5. UVA 11346 - Probability 数学积分

    Consider rectangular coordinate system and point L(X, Y ) which is randomly chosen among all pointsi ...

  6. UI设计师不可不知的安卓屏幕知识-安卓100分享

    http://www.android100.org/html/201505/24/149342.html UI设计师不可不知的安卓屏幕知识-安卓100分享 不少设计师和工程师都被安卓设备纷繁的屏幕搞得 ...

  7. extjs 与html相结合 自定义

    http://skirtlesden.com/articles/html-and-extjs-components

  8. SQLserver中用convert函数转换日期格式(2)

    ), ): :57AM ), ): ), ): ), ): ), ): ), ): ), ): ), ): , ), ): :: ), ): :::827AM ), ): ), ): ), ): ), ...

  9. ROS-SLAM-自主导航

    前言:无. 前提:已下载并编译了相关功能包集,如还未下载,可通过git下载:https://github.com/huchunxu/ros_exploring.git 一.启动仿真环境 cd ~/ca ...

  10. appium连接夜游神的方法

    很多小伙伴想连接夜游神模拟器,但是无法连接,下面是夜游神的链接方法 第一步:先打开夜游神模拟器 第二步:打开运行输入cmd,输入夜游神连接方法:adb connect 127.0.0.1:62001第 ...