1. 程式人生 > >Hibernate多對多操作

Hibernate多對多操作

factory cnblogs all nec ping log per mes lds

1、首先創建兩個實體類(訂單類和商品類)

訂單類:

/**
     * 在多對多關系中,在多的那一方,必須要有一個set集合屬性來保存一個那個實體
     * 並提供共有的getter和setter方法。
     */
    private Set<Good> getSet = new HashSet<Good>();
    
    /**
     * @return the getSet
     */
    public Set<Good> getGetSet() {
        return getSet;
    }
    /**
     * 
@param getSet the getSet to set */ public void setGetSet(Set<Good> getSet) { this.getSet = getSet; }

商品類:

    /**
     * 在多對多關系中,在多的那一方,必須要有一個set集合屬性來保存一個那個實體
     * 並提供共有的getter和setter方法。
     */
    private Set<Order> getOrders = new HashSet<Order>() ;
    public
Set<Order> getGetOrders() { return getOrders; } public void setGetOrders(Set<Order> getOrders) { this.getOrders = getOrders; }

2、配置映射文件

  商品類映射文件

 <hibernate-mapping>
        <class name="com.jack.entity.Good" table="t_good">
            <id 
name="gid" column="gid"> <generator class="native"></generator> </id> <property name="gname" column="gname"></property> <property name="gmessage" column="gmessage"></property> <!-- name屬性的值:該實體中表示另一個實體的set對象名稱 <key>中column屬性的值:第三張表中外鍵的名稱 class屬性的值:另一個類的全路徑 column屬性的值:另一個實體類在第三張表中的外鍵的名稱 --> <set name="getOrders" table="good_order" cascade="save-update,delete"> <key column="goodid"></key> <many-to-many class="com.jack.entity.Order" column="orderid" /> </set> </class> </hibernate-mapping>

訂單類映射文件

 <hibernate-mapping>
        <class name="com.jack.entity.Order" table="t_order">
            <id name="oid" column="oid">
                <generator class="native"></generator>
            </id>
            <property name="oname" column="oname"></property>
            <property name="omessage" column="omessage"></property>
             <!-- 
             name屬性的值:該實體中表示另一個實體的set對象名稱
                 <key>中column屬性的值:第三張表中外鍵的名稱
                 class屬性的值:另一個類的全路徑
                 column屬性的值:另一個實體類在第三張表中的外鍵的名稱
              -->
           <set name="getSet" table="good_order" >
               <key column="orderid"></key>
               <many-to-many class="com.jack.entity.Good" column="goodid" />
           </set>
        </class>
    </hibernate-mapping>

3、編寫核心配置文件

<hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql:///hibernatetest</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root</property>
            
            <property name="hibernate.show_sql">true</property>
            <property name="hibernate.format_sql">true</property>
            <property name="hibernate.hbm2ddl.auto">update</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="hibernate.current_session_context_class">thread</property>
       
            <mapping resource="com/jack/entity/Good.hbm.xml"/>
            <mapping resource="com/jack/entity/Order.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

4、編寫工具類

public class HibernateUtils {
    
    private static Configuration configuration = null;
    private static SessionFactory sessionFactory = null;
    
    
    static{
        configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
    }

    public static Session getSeeion() {
        return sessionFactory.getCurrentSession();
    }
}

5、編寫測試類

    @Test
    public void TestAdd(){
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSeeion();
            tx = session.beginTransaction();
            /**
             * 創建兩個商品
             */
            Good good1 = new Good();
            good1.setGname("蛋糕");
            good1.setGmessage("奶油蛋糕");
            
            Good good2 =new Good();
            good2.setGname("牙膏");
            good2.setGmessage("冷酸靈牙膏");
            /**
             * 創建三個訂單
             */
            Order order1 = new Order();
            order1.setOname("訂單1");
            order1.setOmessage("001111");
            
            Order order2 = new Order();
            order2.setOname("訂單2");
            order2.setOmessage("002222");
            
            Order order3 = new Order();
            order3.setOname("訂單3");
            order3.setOmessage("003333");
            
            /**
             * 建立關系,把訂單放到商品裏
             */
            
            good1.getGetOrders().add(order1);
            good1.getGetOrders().add(order2);
            
            good2.getGetOrders().add(order2);
            good2.getGetOrders().add(order3);
            /**
             * 保存商品
             */
            session.save(good1);
            session.save(good2);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }finally{
            
        }    
    }
    

7、測試結果

技術分享技術分享技術分享

8、級聯刪除

@Test
    public void TestDelete(){
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSeeion();
            tx = session.beginTransaction();
            /**
             * 查找蛋糕
             */
            Good good1 =session.get(Good.class, 1);
        
            /**
             * 刪除蛋糕
             */
    
            session.delete(good1);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }finally{
            
        }    
    }

9、級聯刪除結果

技術分享技術分享技術分享

有結果可見,級聯刪除存在一定的問題,因此在刪除是不使用,而是使用維護第三張表的方式來刪除。

10、維護第三張表

添加維護(將蛋糕加進第三張訂單)

    @Test
    public void TestAdd(){
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSeeion();
            tx = session.beginTransaction();
            /**
             * 查找蛋糕
             */
            Good good1 =session.get(Good.class, 1);
            /**
             * 查找
             */
            Order order3 = session.get(Order.class, 3);
            /**
             * 將訂單放進商品中
             */
            good1.getGetOrders().add(order3);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }finally{
            
        }    
    }

測試結果

技術分享

刪除維護(將蛋糕從第二張訂單刪除)

@Test
    public void TestDelete(){
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtils.getSeeion();
            tx = session.beginTransaction();
            /**
             * 查找蛋糕
             */
            Good good1 =session.get(Good.class, 1);
            /**
             * 查找
             */
            Order order2 = session.get(Order.class, 2);
            /**
             * 將訂單放進商品中
             */
            good1.getGetOrders().remove(order2);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }finally{
            
        }    
    }

測試結果:

技術分享

Hibernate多對多操作