Hibernate框架簡介④

Milky-way發表於2018-08-11

Hibernate的關聯對映:

多對一關聯對映:

第一步: 建立實體模型

Emp類:

package com.rl.hiber.model;

import java.util.Date;

public class Emp {

    private Integer empNo;
    
    private String ename;
    
    private Date birthday;
    
    private Integer gender;
    
    private String address;
    
    /**
     * 引入一的一端作為屬性, 建立多對一的關係
     */
    private Team team;

    public Integer getEmpNo() {
        return empNo;
    }

    public void setEmpNo(Integer empNo) {
        this.empNo = empNo;
    }

    public Team getTeam() {
        return team;
    }

    public void setTeam(Team team) {
        this.team = team;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

Team類:

package com.rl.hiber.model;

public class Team {

    private Integer tId;
    
    private String tName;
    
    private String loc;

    public Integer gettId() {
        return tId;
    }

    public void settId(Integer tId) {
        this.tId = tId;
    }

    public String gettName() {
        return tName;
    }

    public void settName(String tName) {
        this.tName = tName;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }
}

第二步: 配置實體對映檔案

Emp.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Emp" table="t_emp">
        <id name="empNo" column="emp_no">
            <generator class="native"></generator>
        </id>
        <property name="ename"></property>
        <property name="birthday"></property>
        <property name="gender"></property>
        <property name="address"></property>
        
        <!-- 指定多對一的關聯對映
            name: 多的一端中定義的一的一端的屬性, 也就是team
            column: 多的一端中的外來鍵, 也就是一的一端中的主鍵, t_id
         -->
        <many-to-one name="team" column="t_id">
            
        </many-to-one>
    </class>
</hibernate-mapping>        

Team.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Team" table="t_team">
        <id name="tId" column="t_id">
            <generator class="native"></generator>
        </id>
        <property name="tName" column="t_name"></property>
        <property name="loc"></property>
    </class>
    
</hibernate-mapping>        

hibernate.cfg.xml:

生成建表指令碼:

資料庫建表結果:

第三步: 測試多對一關聯對映

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Team;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {

    @Test
    public void test1() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Team team = new Team();
            team.settName("公牛隊");
            team.setLoc("芝加哥");
            //儲存球隊(要先儲存球隊, 否則是瞬時物件)
            session.save(team);
            
            Emp emp1 = new Emp();
            Emp emp2 = new Emp();
            
            emp1.setEname("喬丹");
            emp1.setAddress("芝加哥");
            emp1.setGender(1);
            emp1.setBirthday(new Date());
            //設定隊員與球隊之間的關係
            emp1.setTeam(team);
            //儲存隊員
            session.save(emp1);
            
            emp2.setAddress("芝加哥");
            emp2.setBirthday(new Date());
            emp2.setEname("菲爾");
            emp2.setGender(1);
            emp2.setTeam(team);
            session.save(emp2);
            
            //提交事務
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

hibernate發出sql語句:

資料庫結果:

下面講解一個知識點:

級聯: 在"多的一端"設定cascade屬性

直接貼程式碼吧:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Emp" table="t_emp">
        <id name="empNo" column="emp_no">
            <generator class="native"></generator>
        </id>
        <property name="ename"></property>
        <property name="birthday"></property>
        <property name="gender"></property>
        <property name="address"></property>
        
        <!-- 指定多對一的關聯對映
            name: 多的一端中定義的一的一端的屬性, 也就是team
            column: 多的一端中的外來鍵, 也就是一的一端中的主鍵, t_id
            cascade: delete(刪除多的一端會直接上一的一端也刪除, 即 刪除隊員也會把球隊給刪掉), 在多的一端不建議使用
                    save-update(儲存或者更新多的一端時, 一的一端也會自動先做儲存或更新, 即 不需要先儲存球隊), 建議使用
                    all:包含以上兩種
                    none: 沒有級聯(預設狀態)
         -->
        <many-to-one name="team" column="t_id" cascade="save-update">
            
        </many-to-one>
    </class>
</hibernate-mapping>        

測試級聯狀態為save-update程式碼:

package com.rl.hiber.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Team;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {

    
    
    /**
     * 將級聯狀態設定為save-update時不需要先儲存球隊(一的一端)
     */
    @Test
    public void test2() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Team team = new Team();
            team.settName("小牛隊");
            team.setLoc("達拉斯");
            
            Emp emp1 = new Emp();
            Emp emp2 = new Emp();
            
            emp1.setEname("庫班");
            emp1.setAddress("達拉斯");
            emp1.setGender(1);
            emp1.setBirthday(new Date());
            //設定隊員與球隊之間的關係
            emp1.setTeam(team);
            //儲存隊員
            session.save(emp1);
            
            emp2.setAddress("達拉斯");
            emp2.setBirthday(new Date());
            emp2.setEname("諾維斯基");
            emp2.setGender(1);
            emp2.setTeam(team);
            session.save(emp2);
            
            //提交事務
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

 

hibernate發出sql語句:

資料庫結果:

一對一單端關聯對映:

對映檔案:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="IDCard" table="t_id_card">
    <!-- 
                指定idcard的主鍵名稱, 建議跟emp端的主鍵名稱相同
     -->
        <id name="cardId" column="emp_no">
        <!-- 
                    使用外來鍵的方式來生成主鍵
         -->
            <generator class="foreign">
            <!-- 
                            指定idcard這一端的emp屬性
             -->
                <param name="property">emp</param>
            </generator>
        </id>
        <property name="cardNo" column="card_no"></property>
        <!-- 一對一關聯對映
             name: 指定idcard這一端中定義的另一個一的一端的屬性(即emp)
             constrained: true(即建表外來鍵約束), 當要刪除隊員資訊時必須先刪除idcard
         -->
        <one-to-one name="emp" constrained="true"></one-to-one>
    </class>
</hibernate-mapping>        

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.IDCard;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {

    @Test
    public void testAdd() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Emp emp = new Emp();
            emp.setAddress("廣州");
            emp.setBirthday(new Date());
            emp.setEname("張三");
            emp.setGender(1);
            
            IDCard card = new IDCard();
            card.setCardNo("111");
            card.setEmp(emp);
            //此時並沒有設定級聯, 但hibernate會自動在儲存idcard時先儲存emp
            //因為如果不儲存emp則無法返回主鍵, 它們倆是共用主鍵的以保證一對一關係
            session.save(card);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

資料庫結果:

一對一雙向對映

Emp表的配置檔案:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Emp" table="t_emp">
        <id name="empNo" column="emp_no">
            <generator class="native"></generator>
        </id>
        <property name="ename"></property>
        <property name="birthday"></property>
        <property name="gender"></property>
        <property name="address"></property>
        <!-- 指定一對一關聯對映關係 -->
        <one-to-one name="card"></one-to-one>
    </class>
</hibernate-mapping>        

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.IDCard;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {

    
    @Test
    public void testAdd() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Emp emp = new Emp();
            emp.setAddress("北京");
            emp.setBirthday(new Date());
            emp.setEname("李四");
            emp.setGender(1);
            
            IDCard card = new IDCard();
            card.setCardNo("123");
            
            emp.setCard(card);
            card.setEmp(emp);
            session.save(emp);
            session.save(card);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

資料庫結果同上的一對一單端對映

一對多單向關聯對映:

在多對一的基礎上修改:

Emp配置檔案:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Emp" table="t_emp">
        <id name="empNo" column="emp_no">
            <generator class="native"></generator>
        </id>
        <property name="ename"></property>
        <property name="birthday"></property>
        <property name="gender"></property>
        <property name="address"></property>
        
    </class>
</hibernate-mapping>        

Team配置檔案:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Team" table="t_team">
        <id name="tId" column="t_id">
            <generator class="native"></generator>
        </id>
        <property name="tName" column="t_name"></property>
        <property name="loc"></property>
        
        <!-- 指定一對多關聯對映
            name: 在一的一端指定一個多的一端的集合屬性emps
            key:->column: 多的一端裡面有一個一的一端的外來鍵t_id
            one-to-many:->class: 多的一端所在的位置(預設已經指定了com.rl.hiber.model)
         -->
        <set name="emps">
            <key column="t_id"></key>
            <one-to-many class="Emp"/>
        </set>
    </class>
    
</hibernate-mapping>        

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Team;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {
    
    @Test
    public void testAdd() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Emp emp = new Emp();
            emp.setAddress("芝加哥");
            emp.setBirthday(new Date());
            emp.setEname("喬丹");
            emp.setGender(1);
            //儲存隊員
            session.save(emp);
            
            Emp emp1 = new Emp();
            emp1.setAddress("芝加哥");
            emp1.setBirthday(new Date());
            emp1.setEname("菲爾");
            emp1.setGender(1);
            //
            session.save(emp1);
            
            Set<Emp> emps = new HashSet<Emp>();
            emps.add(emp);
            emps.add(emp1);
            
            Team team = new Team();
            team.setLoc("芝加哥");
            team.settName("公牛隊");
            //指定一對多的關係
            team.setEmps(emps);
            //儲存球隊
            session.save(team);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

資料庫結果:

設定級聯:

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Team;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {
    
    @Test
    public void testAdd() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Emp emp = new Emp();
            emp.setAddress("達拉斯");
            emp.setBirthday(new Date());
            emp.setEname("庫班");
            emp.setGender(1);
            
            Emp emp1 = new Emp();
            emp1.setAddress("達拉斯");
            emp1.setBirthday(new Date());
            emp1.setEname("諾維斯基");
            emp1.setGender(1);
            
            Set<Emp> emps = new HashSet<Emp>();
            emps.add(emp);
            emps.add(emp1);
            
            Team team = new Team();
            team.setLoc("達拉斯");
            team.settName("小牛隊");
            team.setEmps(emps);
            //儲存球隊時就會自動儲存隊員
            session.save(team);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

資料庫結果:

一對多雙向對映:

一對多是有缺陷的, 儲存的時候如果多的一端的外來鍵是非空欄位, 那麼儲存就會出錯.

跟多對一類似, 有點小區別:

需要在一對多的基礎上再在多的一端指定多對一的關係, 就不貼程式碼了

Emp.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Emp" table="t_emp">
        <id name="empNo" column="emp_no">
            <generator class="native"></generator>
        </id>
        <property name="ename"></property>
        <property name="birthday"></property>
        <property name="gender"></property>
        <property name="address"></property>
        <!-- 指定多對一的關聯對映
            name: 多的一端中定義的一的一端的屬性, 也就是team
            column: 多的一端中的外來鍵, 也就是一的一端中的主鍵, t_id
                                        這個外來鍵必須跟team.hbm.xml指定的外來鍵一樣, 如果兩個column的名稱不一樣則相當於有兩個外來鍵就衝突了
         -->
        <many-to-one name="team" column="t_id" />
    </class>
</hibernate-mapping>        

Team.hbm.xml同上

測試程式碼同多對一.

真正的解決非空欄位的方法, 如果真的有需求需要在一的一端進行儲存的話, 可以在Team.hbm.xml設定反轉:
 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Team" table="t_team">
        <id name="tId" column="t_id">
            <generator class="native"></generator>
        </id>
        <property name="tName" column="t_name"></property>
        <property name="loc"></property>
        
        <!-- 指定一對多關聯對映
            name: 在一的一端指定一個多的一端的集合屬性emps
            key:->column: 多的一端裡面有一個一的一端的外來鍵t_id
            one-to-many:->class: 多的一端所在的位置(預設已經指定了com.rl.hiber.model)
            inverser: 設定反轉, 表面上用一的一端進行儲存, 實際上反轉給多的一端進行儲存
         -->
        <set name="emps" cascade="save-update" inverse="true">
            <key column="t_id"></key>
            <one-to-many class="Emp"/>
        </set>
    </class>
    
</hibernate-mapping>        

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Team;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {
    
  
    
    @Test
    public void testAdd2() {
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Team team = new Team();
            team.setLoc("達拉斯");
            team.settName("小牛隊");
            
            Emp emp = new Emp();
            emp.setAddress("達拉斯");
            emp.setBirthday(new Date());
            emp.setEname("庫班");
            emp.setGender(1);
            //利用隊員指定多對一
            emp.setTeam(team);
            
            Emp emp1 = new Emp();
            emp1.setAddress("達拉斯");
            emp1.setBirthday(new Date());
            emp1.setEname("諾維斯基");
            emp1.setGender(1);
            emp1.setTeam(team);
            
            Set<Emp> emps = new HashSet<Emp>();
            emps.add(emp);
            emps.add(emp1);
            
            team.setEmps(emps);
            //只儲存球隊, 實際上會反轉給多的一端進行儲存
            session.save(team);
            
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

結果相同

單端多對多關聯對映:

Emp類需要加上另一端的屬性, 並提供set跟get方法, 就不貼程式碼了

配置檔案:

Emp.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Emp" table="t_emp">
        <id name="empNo" column="emp_no">
            <generator class="native"></generator>
        </id>
        <property name="ename"></property>
        <property name="birthday"></property>
        <property name="gender"></property>
        <property name="address"></property>
        
        <!-- 指定多對多關係
            table: 中間表
         -->
        <set name="roles" table="emp_role">
        <!-- emp端的外來鍵, 也就是emp_no主鍵 -->
            <key column="emp_no"></key>
            <!-- 
                class: 另一端的路徑
                column: 另一端的外來鍵, 也就是role_id主鍵
             -->
            <many-to-many class="Role" column="role_id"></many-to-many>
        </set>
    </class>
</hibernate-mapping>        

Role.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Role" table="t_role">
        <id name="roleId" column="role_id">
            <generator class="native"></generator>
        </id>
        <property name="roleName" column="role_name"></property>
        <property name="roleDesc" column="role_desc"></property>
    </class>
</hibernate-mapping>        

生成資料庫表:

 

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Role;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {
    
    @Test
    public void testAdd() {
        
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            Emp emp = new Emp();
            emp.setAddress("上海");
            emp.setBirthday(new Date());
            emp.setEname("田七");
            emp.setGender(1);
            
            Role role1 = new Role();
            role1.setRoleDesc("講課");
            role1.setRoleName("老師");
            session.save(role1);
            
            Role role2 = new Role();
            role2.setRoleDesc("管理");
            role2.setRoleName("總監");
            session.save(role2);
            
            Set<Role> roles = new HashSet<Role>();
            roles.add(role1);
            roles.add(role2);
            
            emp.setRoles(roles);
            session.save(emp);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

資料庫結果:

同樣也可以設定級聯, 就不舉例了.

 

多對多的雙向關聯:

Role類需要加上另一端的屬性, 並提供set跟get方法

在原來的基礎上修改Role.hbm.xml, 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
        
<hibernate-mapping package="com.rl.hiber.model">
    <class name="Role" table="t_role">
        <id name="roleId" column="role_id">
            <generator class="native"></generator>
        </id>
        <property name="roleName" column="role_name"></property>
        <property name="roleDesc" column="role_desc"></property>
        
        <!-- 指定多對多關係(需中間表) -->
        <set name="emps" table="emp_role" cascade="save-update">
        <!-- key:->column: role端的外來鍵, role_id -->
            <key column="role_id"></key>
            <!-- class: 另一端的路徑  column: 另一端的外來鍵emp_no -->
            <many-to-many class="Emp" column="emp_no"></many-to-many>
        </set>
    </class>
</hibernate-mapping>        

測試程式碼:

package com.rl.hiber.test;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.rl.hiber.model.Emp;
import com.rl.hiber.model.Role;
import com.rl.hiber.utils.HibernateUtil;

public class TestHibernate {
    
    
    
    /**
     * 採用級聯的方式
     */
    @Test
    public void testAdd2() {
        
        Session session = HibernateUtil.getSessoion();
        Transaction tx = session.beginTransaction();
        
        try {
            
            Emp emp = new Emp();
            emp.setAddress("上海");
            emp.setBirthday(new Date());
            emp.setEname("田七");
            emp.setGender(1);
            
            Emp emp2 = new Emp();
            emp2.setAddress("天津");
            emp2.setBirthday(new Date());
            emp2.setEname("周八");
            emp2.setGender(2);
            
            Set<Emp> emps = new HashSet<Emp>();
            emps.add(emp);
            emps.add(emp2);
            
            Role role1 = new Role();
            role1.setRoleDesc("講課");
            role1.setRoleName("老師");
            role1.setEmps(emps);
            session.save(role1);
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
            tx.rollback();
        }finally {
            HibernateUtil.closeResource(session);
        }
    }
}

資料庫結果:

相關文章