hibernate一对多关联关系配置经验

假使有一个order表和一个customer表,那么它们两者的关系是一个customer可以有多个order,一个order只能属于一个customer,在hibernate中,他们的配置如下:

Xml代码
  1. <?xmlversion="1.0"?>
  2. <!DOCTYPEhibernate-mapping
  3. PUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <classname="mypack.Customer"table="CUSTOMERS">
  7. <idname="id"type="long"column="ID">
  8. <generatorclass="increment"/>
  9. </id>
  10. <propertyname="name"type="string">
  11. <columnname="NAME"length="15"/>
  12. </property>
  13. <!--
  14. <set
  15. name="orders"
  16. cascade="all-delete-orphan"
  17. inverse="true"
  18. >
  19. <keycolumn="CUSTOMER_ID"/>
  20. <one-to-manyclass="mypack.Order"/>
  21. </set>
  22. -->
  23. <set
  24. name="orders"
  25. inverse="true"
  26. cascade="save-update"
  27. >
  28. <keycolumn="CUSTOMER_ID"/>
  29. <one-to-manyclass="mypack.Order"/>
  30. </set>
  31. </class>
  32. </hibernate-mapping>

Xml代码
  1. <?xmlversion="1.0"?>
  2. <!DOCTYPEhibernate-mapping
  3. PUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <classname="mypack.Order"table="ORDERS">
  7. <idname="id"type="long"column="ID">
  8. <generatorclass="increment"/>
  9. </id>
  10. <propertyname="orderNumber"type="string">
  11. <columnname="ORDER_NUMBER"length="15"/>
  12. </property>
  13. <many-to-one
  14. name="customer"
  15. column="CUSTOMER_ID"
  16. class="mypack.Customer"
  17. cascade="save-update"
  18. />
  19. </class>
  20. </hibernate-mapping>

他们的业务类中则有以下方法:

Java代码
  1. packagemypack;
  2. importorg.hibernate.*;
  3. importorg.hibernate.cfg.Configuration;
  4. importjava.util.*;
  5. publicclassBusinessService{
  6. publicstaticSessionFactorysessionFactory;
  7. privateLongidOfTom;
  8. privateLongidOfTomOrder;
  9. privateLongidOfJack;
  10. privateLongidOfJackOrder;
  11. static{
  12. try{
  13. Configurationconfig=newConfiguration();
  14. config.configure();
  15. sessionFactory=config.buildSessionFactory();
  16. }catch(RuntimeExceptione){e.printStackTrace();throwe;}
  17. }
  18. publicvoidprintOrdersOfCustomer(LongcustomerId){
  19. Sessionsession=sessionFactory.openSession();
  20. Transactiontx=null;
  21. try{
  22. tx=session.beginTransaction();
  23. Customercustomer=(Customer)session.get(Customer.class,customerId);
  24. printOrders(customer.getOrders());
  25. tx.commit();
  26. }catch(RuntimeExceptione){
  27. if(tx!=null){
  28. tx.rollback();
  29. }
  30. throwe;
  31. }finally{
  32. session.close();
  33. }
  34. }
  35. publicvoidsaveCustomerAndOrderWithCascade(){
  36. Sessionsession=sessionFactory.openSession();
  37. Transactiontx=null;
  38. try{
  39. tx=session.beginTransaction();
  40. Customercustomer=newCustomer("Tom",newHashSet());
  41. Orderorder=newOrder();
  42. order.setOrderNumber("Tom_Order001");
  43. order.setCustomer(customer);
  44. customer.getOrders().add(order);
  45. session.save(customer);
  46. tx.commit();
  47. idOfTom=customer.getId();
  48. idOfTomOrder=order.getId();
  49. }catch(RuntimeExceptione){
  50. if(tx!=null){
  51. tx.rollback();
  52. }
  53. e.printStackTrace();
  54. }finally{
  55. session.close();
  56. }
  57. }
  58. publicvoidassociateCustomerAndOrder(){
  59. Sessionsession=sessionFactory.openSession();
  60. Transactiontx=null;
  61. try{
  62. tx=session.beginTransaction();
  63. Customercustomer=(Customer)session.load(Customer.class,idOfJack);
  64. Orderorder=(Order)session.load(Order.class,idOfJackOrder);
  65. order.setCustomer(customer);
  66. customer.getOrders().add(order);
  67. tx.commit();
  68. }catch(RuntimeExceptione){
  69. if(tx!=null){
  70. tx.rollback();
  71. }
  72. e.printStackTrace();
  73. }finally{
  74. session.close();
  75. }
  76. }
  77. publicvoidsaveCustomerAndOrderSeparately(){
  78. Sessionsession=sessionFactory.openSession();
  79. Transactiontx=null;
  80. try{
  81. tx=session.beginTransaction();
  82. Customercustomer=newCustomer();
  83. customer.setName("Jack");
  84. Orderorder=newOrder();
  85. order.setOrderNumber("Jack_Order001");
  86. session.save(customer);
  87. session.save(order);
  88. tx.commit();
  89. idOfJack=customer.getId();
  90. idOfJackOrder=order.getId();
  91. }catch(RuntimeExceptione){
  92. if(tx!=null){
  93. tx.rollback();
  94. }
  95. e.printStackTrace();
  96. }finally{
  97. session.close();
  98. }
  99. }
  100. publicvoiddeleteCustomer(LongcustomerId){
  101. Sessionsession=sessionFactory.openSession();
  102. Transactiontx=null;
  103. try{
  104. tx=session.beginTransaction();
  105. Customercustomer=(Customer)session.load(Customer.class,customerId);
  106. session.delete(customer);
  107. tx.commit();
  108. }catch(RuntimeExceptione){
  109. if(tx!=null){
  110. tx.rollback();
  111. }
  112. e.printStackTrace();
  113. }finally{
  114. session.close();
  115. }
  116. }
  117. publicvoidremoveOrderFromCustomer(LongcustomerId){
  118. Sessionsession=sessionFactory.openSession();
  119. Transactiontx=null;
  120. try{
  121. tx=session.beginTransaction();
  122. Customercustomer=(Customer)session.load(Customer.class,customerId);
  123. Orderorder=(Order)customer.getOrders().iterator().next();
  124. //½â³ýCustomerºÍOrderµÄ¹ØÁª¹Øϵ
  125. customer.getOrders().remove(order);
  126. order.setCustomer(null);
  127. tx.commit();
  128. }catch(RuntimeExceptione){
  129. if(tx!=null){
  130. tx.rollback();
  131. }
  132. e.printStackTrace();
  133. }finally{
  134. session.close();
  135. }
  136. }
  137. publicvoidprintOrders(Setorders){
  138. for(Iteratorit=orders.iterator();it.hasNext();){
  139. Orderorder=(Order)it.next();
  140. System.out.println("OrderNumberof"+order.getCustomer().getName()+":"+order.getOrderNumber());
  141. }
  142. }
  143. publicvoidsaveCustomerAndOrderWithInverse(){
  144. saveCustomerAndOrderSeparately();
  145. associateCustomerAndOrder();
  146. }
  147. publicvoidtest(){
  148. saveCustomerAndOrderWithCascade();
  149. saveCustomerAndOrderWithInverse();
  150. printOrdersOfCustomer(idOfTom);
  151. deleteCustomer(idOfJack);
  152. removeOrderFromCustomer(idOfTom);
  153. }
  154. publicstaticvoidmain(Stringargs[]){
  155. newBusinessService().test();
  156. sessionFactory.close();
  157. }
  158. }

由以上代码执行时的效率和打印的sql语句,我们可以得出以下经验:1.应把one的一方的<set>元素的inverse属性,设置为true,因此hibernate不会因为customer对象的属性变化来同步更新数据库,以提高性能。 2.在建立关联关系之后,在进行更新操作的时候,最好操作关联两端的对象的相关属性。如:

Java代码
  1. order.setCustomer(customer);
  2. customer.getOrders().add(order);

这样会是程序更加健壮,提高业务逻辑的独立性,使代码不收hibernate实现的影像。同理,当解除双向关联关系时,也该操作关联双发的对应属性,如:

Java代码
  1. customer.getOrders().remove(order);
  2. order.setCustomer(null);

你可能感兴趣的:(Hibernate)