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();
    }

}

 

posted @ 2018-03-31 15:11  彩电  阅读(314)  评论(0编辑  收藏  举报