1. 程式人生 > >Hibernate框架之路(二)一對多關系

Hibernate框架之路(二)一對多關系

true pre conn 關系 編寫 none isp exce dia

在下列案例中:

  客戶是一;聯系人是多;客戶可以擁有多個聯系人;一個聯系人只有一個客戶

  1、編寫實體類

技術分享
package com.pojo;

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

public class User {
    private Integer uId;    //客戶ID(主表)    客戶是一
    private String uName;    //名字
    private String uTel;    //手機
//    在客戶的表中顯示多個聯系人
//    使用set集合存儲聯系人
private Set<Link> link = new HashSet<Link>(); public Set<Link> getLink() { return link; } public void setLink(Set<Link> link) { this.link = link; } public Integer getuId() { return uId; } public void setuId(Integer uId) {
this.uId = uId; } public String getuName() { return uName; } public void setuName(String uName) { this.uName = uName; } public String getuTel() { return uTel; } public void setuTel(String uTel) { this.uTel = uTel; } }
User實體類
技術分享
package com.pojo;

public class Link {
    private Integer cId;    //聯系人ID    聯系人是多
    private String cName;    //姓名
    private String cTel;    //電話
    //在聯系人的實體類中顯示所屬客戶列表;一個聯系人只有一個客戶
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public Integer getcId() {
        return cId;
    }
    public void setcId(Integer cId) {
        this.cId = cId;
    }
    public String getcName() {
        return cName;
    }
    public void setcName(String cName) {
        this.cName = cName;
    }
    public String getcTel() {
        return cTel;
    }
    public void setcTel(String cTel) {
        this.cTel = cTel;
    }
}
聯系人實體類

  2、配置實體類映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <!-- 客戶配置文件 -->
        <class name="com.pojo.User" table="p_user">
            <id name="uId" column="uId">
                <generator class="native"></generator>
            </id>
            <property name="uName" column="uName"></property>
            <property name="uTel" column="uTel"></property>
            <!-- set標簽的name屬性:指的是寫在客戶表中的聯系人的set集合的名稱 
                inverse="true":讓主表一方放棄維護
            -->
            <set name="link" cascade="save-update,delete" inverse="false">
            <!-- id 的 column 屬性的值:數據表的外鍵名稱 -->
                <key column="clid"></key>
                <!-- 客戶的所有聯系人; class寫聯系人的實體類路徑 -->
                <one-to-many class="com.pojo.Link"/>
            </set>
        </class>
    </hibernate-mapping>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    <!-- 聯系人配置文件 -->
        <class name="com.pojo.Link" table="p_link">
            <id name="cId" column="cId">
                <generator class="native"></generator>
            </id>
            <property name="cName" column="cName"></property>
            <property name="cTel" column="cTel"></property>
            <!-- 聯系人所屬客戶
                name:客戶在聯系人實體類的屬性
                class:聯系人實體類的路徑
                column:外鍵名稱
             -->
             <many-to-one name="user" class="com.pojo.Link" column="clid"></many-to-one>
        </class>
    </hibernate-mapping>

  3、配置核心文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- 1、配置數據庫信息  必寫的 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///person</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!-- 2、配置hibernate信息   可寫   -->
        <!-- 輸出SQL底層語句  -->
        <property name="hibernate.show_sql">true</property>        
        <!-- 輸出SQL底層語句  進行格式化 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 如果沒有表。即創建,否則修改表  -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 設置數據庫方言  -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <!-- 3、把映射文件放到核心配置文件中 必須的  -->
        <mapping resource="com/pojo/Link.hbm.xml"/>
        <mapping resource="com/pojo/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

  4、加載核心配置文件測試是否搭建成功

package com.unitl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    private static Configuration cfg = null;
    private static SessionFactory factory = null;
    static{
        // 加載 hibernate 核心文件
        cfg = new Configuration();    
        cfg.configure();
        // 創建 SessionFactory對象
        factory = cfg.buildSessionFactory();
    }
    //獲取 hibernate核心文件
    public static SessionFactory getSessionFactory() {
        return factory;    
    }
    //綁定本地線程session
    public static Session getSessionObject(){
        return factory.getCurrentSession();
    }
    /**
     * 調用方法
     *     SessionFactory factory = HibernateUtils.getSessionFactory();
     * 
     */
    public static void main(String[] args) {
        //執行之後無報錯,則配置成功
    }
}

  5、使用方法實現增刪改查操作

技術分享
package com.junit;

import static org.junit.Assert.*;

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

import com.pojo.Link;
import com.pojo.User;
import com.unitl.HibernateUtils;

public class Text1 {

    @Test
    public void test() {
        SessionFactory factory = null;
        Session session = null;
        Transaction ts = null;
        try {
            factory = HibernateUtils.getSessionFactory();
            session = factory.openSession();
            ts = session.beginTransaction();
            /**
             * 創建聯系人
             */
            Link link1 = new Link();
            link1.setcName("百度");    
            link1.setcTel("400-200-666");
            /**
             * 創建客戶
             */
            User user1 = new User();
            user1.setuName("張三");
            user1.setuTel("150*******");
            /**
             * 把聯系人對象放到客戶的set集合裏邊
             */
            user1.getLink().add(link1);
            /**
             * 把客戶放在聯系人對象裏
             */
            link1.setUser(user1);
            //添加到數據庫
            session.save(user1);
            session.save(link1);
            //提交事務
            ts.commit();
        } catch (Exception e) {
            ts.rollback();
        } finally {
            session.close();
            factory.close();
        }
    }
    /**
     * 簡化
     * 添加操作
     */
    @Test
    public void test2() {
        SessionFactory factory = null;
        Session session = null;
        Transaction ts = null;
        try {
            factory = HibernateUtils.getSessionFactory();
            session = factory.openSession();
            ts = session.beginTransaction();
            //添加一個客戶
            User user1 = new User();
            user1.setuName("李四");
            user1.setuTel("150*******");
            //創建聯系人
            Link link1 = new Link();
            link1.setcName("騰訊");    
            link1.setcTel("400-200-666");
            //把聯系人放到客戶的 set 集合裏邊
            user1.getLink().add(link1);
            // 保存到 數據庫裏
            session.save(user1);
            ts.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ts.rollback();
        }finally{
            session.close();
            factory.close();
        }
    }
    /**
     * 添加一個聯系人到已知的客戶裏
     * 例子:向一個已知店鋪裏添加一個商品
     */
    @Test
    public void test3() {
        SessionFactory factory = null;
        Session session = null;
        Transaction ts = null;
        try {
            factory = HibernateUtils.getSessionFactory();
            session = factory.openSession();
            ts = session.beginTransaction();
            //創建一個聯系人並添加到已知客戶
            Link link1 = new Link();
            link1.setcName("阿裏巴巴");    
            link1.setcTel("400-200-666");
            //獲取客戶
            User user = session.get(User.class,2);
            user.getLink().add(link1);
            session.save(user);
            ts.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ts.rollback();
        }finally{
            session.close();
            factory.close();
        }
    }
    /**
     * 刪除一個客戶
     */
    @Test
    public void test4() {
        SessionFactory factory = null;
        Session session = null;
        Transaction ts = null;
        try {
            factory = HibernateUtils.getSessionFactory();
            session = factory.openSession();
            ts = session.beginTransaction();
            //查詢客戶ID
            User user = session.get(User.class, 3);
            session.delete(user);
            ts.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ts.rollback();
        }finally{
            session.close();
            factory.close();
        }
    }
    /**
     * 修改操作
     * 把聯系人表中的ID為2的聯系人改為客戶一的聯系人
     */
    @Test
    public void test5() {
        SessionFactory factory = null;
        Session session = null;
        Transaction ts = null;
        try {
            factory = HibernateUtils.getSessionFactory();
            session = factory.openSession();
            ts = session.beginTransaction();
            //查詢聯系人ID和用戶ID
            User user = session.get(User.class, 1);
            Link link = session.get(Link.class, 2);
//        把聯系人放到客戶裏邊;客戶放到聯系人裏
            user.getLink().add(link);
            link.setUser(user);
            ts.commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ts.rollback();
        }finally{
            session.close();
            factory.close();
        }
    }
}
View Code

Hibernate框架之路(二)一對多關系