Hibernate三种实体映射,从建表到操作代码

这里写图片描述
映射关联大致分为三种 :
一对一 ,一对多, 多对多
一.一对一

drop table if exists husband;
create table husband(
   id int not null  primary key ,
   hname varchar(20) not null collate 'utf8_bin'
);
drop table if exists wife;
create table wife(
   id int not null  primary key ,
   wname varchar(20) not null collate 'utf8_bin',
   constraint h_w_id foreign key(id)references husband(id)
)

这里写图片描述

package com.lyf.dao;


import com.lyf.po.Hus;
import com.lyf.po.Wif;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

/**
 * Created by fangjiejie on 2017/4/16.
 */
public class HusDao implements IHusDao{
    private Configuration cfg=null;
    private SessionFactory sf=null;

    public HusDao() {
        cfg=new Configuration().configure("hibernate.cfg.xml");
        sf=cfg.buildSessionFactory();
    }
@Test
    public void add() {
        Session session=null;
        Transaction tran=null;
        try {
            session=sf.openSession();
            tran=session.getTransaction();
            tran.begin();
            Hus hus=new Hus();
            hus.setId(3);
            hus.sethName("hus2");
            Wif wif=new Wif();
            wif.setId(3);
            wif.setwName("wif2");
            wif.setHus(hus);
            hus.setWif(wif);
            session.save(hus);
            tran.commit();

        } catch (HibernateException e) {
            tran.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }

    }
@Test
    public void delete() {
        Session session=sf.openSession();
        Transaction tran=session.getTransaction();
        tran.begin();
         Hus h=session.load(Hus.class,3);
         session.delete(h);
        tran.commit();
        session.close();
    }
@Test
    public void update() {
        Session session=sf.openSession();
        Transaction tran=session.getTransaction();
        tran.begin();
        Hus h=session.load(Hus.class,1);
        h.sethName("hus0");
        h.getWif().setwName("wif0");
        session.update(h);
        tran.commit();
        session.close();
    }
@Test
    public void query() {
        Session session=sf.openSession();
        Hus h=session.load(Hus.class,1);
        System.out.printf("Hus:%s Wife:%s",h.gethName(),h.getWif().getwName());

        session.close();
    }
}

想要实现对主表操作,从表也跟着操作 可以设置hus实体

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
    public Wif getWif() {
        return wif;
    }

    public void setWif(Wif wif) {
        this.wif = wif;
    }
}

二.一对多

drop table if exists father;
create table father(
   fid int not null  primary key ,
   fname varchar(20) not null collate 'utf8_bin'
);
drop table if exists son;
create table son(
   sid int not null  primary key ,
   sname varchar(20) not null collate 'utf8_bin',
   fid int not null,
   constraint f_s_id foreign key(fid)references father(fid)
)

这里写图片描述

package com.lyf.dao;

import com.lyf.po.Father;
import com.lyf.po.Son;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import java.util.Iterator;
import java.util.Set;


/**
 * Created by fangjiejie on 2017/4/17.
 */
public class FaterDal implements IFather{
    private Configuration cfg=null;
    private SessionFactory sf=null;

    public FaterDal() {
        cfg=new Configuration().configure("hibernate.cfg.xml");
        sf=cfg.buildSessionFactory();
    }
@Test
    public void add() {
        Session session=sf.openSession();
        Transaction tran=session.getTransaction();
        tran.begin();
    Father f1=new Father();
    f1.setfId(7);
    f1.setfName("f7");

    Son s1=new Son();
    s1.setsId(5);
    s1.setsName("s5");
    s1.setFather(f1);
    Son s2=new Son();
    s2.setsId(6);
    s2.setsName("s6");
    s2.setFather(f1);
    f1.getSons().add(s1);
    f1.getSons().add(s2);
    session.save(f1);
        tran.commit();
        session.close();
    }
@Test
    public void delete() {
        Session session=sf.openSession();
        Transaction tran=session.getTransaction();
        tran.begin();
        Father f=session.load(Father.class,7);
        session.delete(f);
        tran.commit();
        session.close();
    }

    public void update() {

    }
@Test
    public void query() {
       Session session=sf.openSession();
        Father f=session.load(Father.class,7);
        Set<Son> sons=f.getSons();
        Iterator<Son> it=sons.iterator();
        while(it.hasNext()){
            Son son=it.next();
            System.out.println(son.getsName());
        }
    session.close();
    }
}

实现主表操作,连动从表,设置father实体类中

@OneToMany(mappedBy = "father",cascade = CascadeType.ALL)
    public Set<Son> getSons() {
        return sons;
    }

    public void setSons(Set<Son> sons) {
        this.sons = sons;

三.多对多

drop table if exists teacher;
create table teacher(
   tid int not null  primary key ,
   tname varchar(20) not null collate 'utf8_bin'
);
drop table if exists student;
create table student(
   sid int not null  primary key ,
   sname varchar(20) not null collate 'utf8_bin'
);
create table teacherstudent(
  tid int not null,
  sid int not null,
  primary key(tid,sid),
  constraint t_s_1 foreign key(tid) references teacher(tid),
  constraint t_s_2 foreign key(sid) references student(sid)
)

这里写图片描述

package com.lyf.dao;

import com.lyf.po.Students;
import com.lyf.po.Teachers;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;


/**
 * Created by fangjiejie on 2017/4/17.
 */
public class StudentsDao implements IStudentsDao {
    private Configuration cfg=null;
    private SessionFactory sf=null;

    public StudentsDao() {
        cfg=new Configuration().configure("hibernate.cfg.xml");
        sf=cfg.buildSessionFactory();
    }
@Test
    public void add() {
        Session session=sf.openSession();
        Transaction tran=session.getTransaction();
        tran.begin();
        Teachers tea1=new Teachers();
        tea1.settId(1);
        tea1.settName("t1");
        Teachers tea2=new Teachers();
        tea2.settId(2);
        tea2.settName("t2");

        Students stu1=new Students();
        stu1.setsId(1);
        stu1.setsName("s1");
        Students stu2=new Students();
        stu2.setsId(2);
        stu2.setsName("s2");

        tea1.getStudents().add(stu1);
        tea1.getStudents().add(stu2);
        tea2.getStudents().add(stu1);
        tea2.getStudents().add(stu2);
        stu1.getTeachers().add(tea1);
        stu1.getTeachers().add(tea2);
        stu2.getTeachers().add(tea1);
        stu2.getTeachers().add(tea2);

        session.save(stu1);
        session.save(stu2);
        tran.commit();
        session.close();
    }
@Test
    public void delete() {
        Session session=sf.openSession();
        Transaction tran=session.getTransaction();
        tran.begin();
        Students s=session.load(Students.class,1);
        session.delete(s);
        tran.commit();
        session.close();
    }

    public void update() {

    }

    public void query() {

    }
}

值得注意的是,如果在删除主表数据时,我们并不想,让从表数据一起删除。我们可以设置主表

 @ManyToMany(cascade = CascadeType.PERSIST)//增加连动,删除不联动
    @JoinTable(name = "teastu", catalog = "bz", schema = "bz", joinColumns = @JoinColumn(name = "s_id", referencedColumnName = "s_id", nullable = false), inverseJoinColumns = @JoinColumn(name = "t_id", referencedColumnName = "t_id", nullable = false))
    public Set<Teachers> getTeachers() {
        return teachers;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值