Rhythmk 学习 Hibernate 05 - Hibernate 表间关系 [ManyToOne,OneToMany]
1、項目結構:
? ? ?
1.1、場景說明: 一個訂單,包含多個產品
1.2、類文件:
? ??Order.java?
package com.rhythmk.model;import java.util.Date;public class Order {public int getOrderID() {return orderID;}public void setOrderID(int orderID) {this.orderID = orderID;}public String getName() {return Name;}public void setName(String name) {Name = name;}public double getSumMoney() {return SumMoney;}public void setSumMoney(double sumMoney) {SumMoney = sumMoney;}public Date getCreateDate() {return createDate;}public void setCreateDate(Date createDate) {this.createDate = createDate;}private int orderID;private String Name;private double SumMoney;@Overridepublic String toString() {return "Order [orderID=" + orderID + ", Name=" + Name + ", SumMoney="+ SumMoney + ", createDate=" + createDate + "]";}private Date createDate;}order.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.rhythmk.model.Order" table="t_order"><id name="orderID" type="int"><column name="orderID" /><generator class="native" /></id><property name="Name" type="string"><column name="Name" not-null="true" /></property><property name="SumMoney" type="double"></property><property name="createDate" type="timestamp"><column name="createDate" not-null="true" /></property></class> </hibernate-mapping>? ??Product.java
package com.rhythmk.model;public class Product {public int getProductID() {return productID;}public void setProductID(int productID) {this.productID = productID;}public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}private int productID;private String productName;public Order getOrder() {return order;}public void setOrder(Order order) {this.order = order;}private Order order ;@Overridepublic String toString() {return "Product [productID=" + productID + ", productName="+ productName + ", order=" + order + "]";}}product.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.rhythmk.model.Product" table="t_product"><id name="productID" type="int"><column name="productID" /><generator class="native" /></id><property name="productName" type="string"><column name="productName" /></property><many-to-one name="order" column="orderID"></many-to-one> </class> </hibernate-mapping>hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration><session-factory><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="connection.url">jdbc:mysql://localhost:3306/hibernate_demo</property><property name="connection.username">root</property><property name="connection.password">wangkun</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property><!--是否在后臺顯示Hibernate用到的SQL語句,開發(fā)時設置為true,便于差錯,程序運行時可以在Eclipse的控制臺顯示Hibernate的執(zhí)行Sql語句。項目部署后可以設置為false,提高運行效率 --><property name="hibernate.show_sql">true </property><property name="hibernate.hbm2ddl.auto">update</property><mapping resource="com/rhythmk/model/user.hbm.xml" /><mapping resource="com/rhythmk/model/product.hbm.xml" /> <mapping resource="com/rhythmk/model/order.hbm.xml" /></session-factory></hibernate-configuration>?
1.3 ?、結論:
? ? ? ? 在Many方 定義XML配置 ?:
<many-to-one name="order" column="orderID"></many-to-one>? ?寫入數據調用session.save方法跟單表保存基本一致。
? ?讀取數據:獲取Many對象,默認 One對象都是以延遲加載模式進行加載。
? ? 不論是刪除 Many ,還是刪除 One 對象 都只刪除本身數據 ,并非刪除全部主從數據,如果刪除One對象,一旦Many還有關聯(lián)One的對象的存在,則將拋出異常。見(test04_del)
?1.4 ?、測試驗證:
@Testpublic void test02_add() {Session session = null;try {session = HibernateUtil.getSessionFactory().openSession();session.beginTransaction();Order order = new Order();order.setCreateDate(new Date());order.setName("訂單一");order.setSumMoney(12);session.save(order);Product p1 = new Product();p1.setOrder(order);p1.setProductName("產品1");session.save(p1);Product p2 = new Product();p2.setOrder(order);p2.setProductName("產品2");session.save(p2);session.getTransaction().commit();} catch (Exception e) {e.printStackTrace();} finally {if (session != null)session.close();}}輸出:
Hibernate: insert into t_order (Name, SumMoney, createDate) values (?, ?, ?)
Hibernate: insert into t_product (productName, orderID) values (?, ?)
Hibernate: insert into t_product (productName, orderID) values (?, ?)
輸出:
Hibernate: select order0_.orderID as orderID1_0_0_, order0_.Name as Name2_0_0_, order0_.SumMoney as SumMoney3_0_0_, order0_.createDate as createDa4_0_0_ from t_order order0_ where order0_.orderID=?
Order [orderID=1, Name=訂單一, SumMoney=12.0, createDate=2014-05-02 15:24:02.0]
-----------Read Product-----------
-----------Print Product-----------
Hibernate: select product0_.productID as productI1_1_0_, product0_.productName as productN2_1_0_, product0_.orderID as orderID3_1_0_ from t_product product0_ where product0_.productID=?
Product [productID=1, productName=產品1, order=Order [orderID=1, Name=訂單一, SumMoney=12.0, createDate=2014-05-02 15:24:02.0]]
-----------Read Order-----------
訂單一
輸出:
-----------Read Product-----------
Hibernate: select product0_.productID as productI1_1_0_, product0_.productName as productN2_1_0_, product0_.orderID as orderID3_1_0_ from t_product product0_ where product0_.productID=?
-----------Print Product-----------
Hibernate: select order0_.orderID as orderID1_0_0_, order0_.Name as Name2_0_0_, order0_.SumMoney as SumMoney3_0_0_, order0_.createDate as createDa4_0_0_ from t_order order0_ where order0_.orderID=?
Product [productID=1, productName=產品1, order=Order [orderID=1, Name=訂單一, SumMoney=12.0, createDate=2014-05-02 15:24:02.0]]
-----------Read Order-----------
訂單一
??
@Testpublic void test04_Del() {Session session = null;try {session = HibernateUtil.getSessionFactory().openSession();session.beginTransaction();/*Product product = (Product) session.get(Product.class, 1);session.delete(product);輸出:Hibernate: select product0_.productID as productI1_1_0_, product0_.productName as productN2_1_0_, product0_.orderID as orderID3_1_0_ from t_product product0_ where product0_.productID=?Hibernate: delete from t_product where productID=?*/ Order order = (Order) session.get(Order.class, 3);session.delete(order);session.getTransaction().commit();} catch (Exception e) {e.printStackTrace();} finally {if (session != null)session.close();}}輸出:
Hibernate: select order0_.orderID as orderID1_0_0_, order0_.Name as Name2_0_0_, order0_.SumMoney as SumMoney3_0_0_, order0_.createDate as createDa4_0_0_ from t_order order0_ where order0_.orderID=?
Hibernate: delete from t_order where orderID=?
org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
?
-------------------------------------------------OneToMany----------------------------------------------------------------------------
>>> OneToMany ?單相關聯(lián)
?
?
2.1 ??
?需求背景:
? ?每個人都有很多標簽:
在User 類中添加:
?
public Set<Tag> getTags() {return tags;}public void setTags(Set<Tag> tags) {this.tags = tags;}private Set<Tag> tags;?
同時 添加 Tag類:
package com.rhythmk.model;public class Tag {public Integer getTagId() {return tagId;}public void setTagId(Integer tagId) {this.tagId = tagId;}public String getTagTitle() {return tagTitle;}public void setTagTitle(String tagTitle) {this.tagTitle = tagTitle;}public Integer getUserID() {return userID;}@Overridepublic String toString() {return "Tag [tagId=" + tagId + ", tagTitle=" + tagTitle + ", userID="+ userID + "]";}public void setUserID(Integer userID) {this.userID = userID;} private Integer tagId;private String tagTitle;private Integer userID; }
?
添加User對應XML配置:
?
<set name="tags"><key column="userID"></key><!-- 此處需要配置完成的類別--><one-to-many class="com.rhythmk.model.Tag" /></set>?
注意:此處 one-to-many 對應的 class 需要填寫類的全路徑名稱
2.2 ?驗證:
@Testpublic void test01_add() {Session session = null;try {session = HibernateUtil.getSessionFactory().openSession();session.beginTransaction();Tag t1 = new Tag();t1.setTagTitle("tag1");Tag t2 = new Tag();t2.setTagTitle("tag2");Set<Tag> tags = new HashSet<Tag>();tags.add(t1);tags.add(t2);User entity = new User();entity.setUserName("張飛2222");entity.setCreateTime(new Date());entity.setTags(tags);session.save(t1);session.save(t2);session.save(entity);session.getTransaction().commit();} catch (Exception e) {e.printStackTrace();} finally {if (session != null)session.close();}}輸出:
Hibernate: insert into t_tag (tagTitle) values (?)
Hibernate: insert into t_tag (tagTitle) values (?)
Hibernate: insert into t_user (userName, createTime) values (?, ?)
Hibernate: update t_tag set userID=? where tagId=?
Hibernate: update t_tag set userID=? where tagId=?
輸出:
------01 -----------
Hibernate: select user0_.userID as userID1_3_0_, user0_.userName as userName2_3_0_, user0_.createTime as createTi3_3_0_ from t_user user0_ where user0_.userID=?
------02 -----------
Hibernate: select tags0_.userID as userID3_3_0_, tags0_.tagId as tagId1_2_0_, tags0_.tagId as tagId1_2_1_, tags0_.tagTitle as tagTitle2_2_1_ from t_tag tags0_ where tags0_.userID=?
Tag [tagId=2, tagTitle=tag1, userID=null]
Tag [tagId=3, tagTitle=tag2, userID=null]
?
?>>>?OneToMany ?雙相關聯(lián)
背景:一個標簽下有多少人
調整原標簽代碼:
?
<set name="users"><key column="tagId"></key><!-- 此處需已在hibernate-mapping 上配置了 類包名--><one-to-many class="User" /></set>?
one-to-many ?class僅填寫類名 現(xiàn)將包名調整到 hibernate-mapping屬性上 如:
<hibernate-mapping package="com.rhythmk.model">調整 Tag.java,添加:
public Set<User> getUsers() {return users;}public void setUsers(Set<User> users) {this.users = users;}private Set<User> users;測試:
@Testpublic void test01_add() {Session session = null;try {session = HibernateUtil.getSessionFactory().openSession();session.beginTransaction();Tag t1 = new Tag();t1.setTagTitle("tag1");Tag t2 = new Tag();t2.setTagTitle("tag2");Set<Tag> tags = new HashSet<Tag>();tags.add(t1);tags.add(t2);User u1 = new User();u1.setUserName("張飛2222");u1.setCreateTime(new Date());u1.setTags(tags);User u2 = new User();u2.setUserName("張飛2333332");u2.setCreateTime(new Date());u2.setTags(tags);Set<User> users = new HashSet<User>();users.add(u1);users.add(u2);t1.setUsers(users);t2.setUsers(users);session.save(t1);session.save(t2);session.save(u1);session.save(u2);session.getTransaction().commit();} catch (Exception e) {e.printStackTrace();} finally {if (session != null)session.close();}}輸出:
?
Hibernate: insert into t_tag (tagTitle) values (?)
Hibernate: insert into t_tag (tagTitle) values (?)
Hibernate: insert into t_user (userName, createTime) values (?, ?)
Hibernate: insert into t_user (userName, createTime) values (?, ?)
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_tag set userID=? where tagId=?
Hibernate: update t_tag set userID=? where tagId=?
Hibernate: update t_tag set userID=? where tagId=?
Hibernate: update t_tag set userID=? where tagId=?
注意:此處因為在提交事務過程中 Tag 以及User都相互影響變化,故出現(xiàn)12條SQL。
? ?在實際項目中 我們并非需要 One 跟 Many都同時去維護數據,故引入?inverse,當inverse="true" 則不去維護對應關系,現(xiàn)修改User.hbm.xml ?如下:
<set name="tags" lazy="extra" inverse="true"><key column="userID"></key><!-- 此處需要配置完成的類別--><one-to-many class="com.rhythmk.model.Tag" /></set>執(zhí)行測試輸出:
Hibernate: insert into t_tag (tagTitle) values (?)
Hibernate: insert into t_tag (tagTitle) values (?)
Hibernate: insert into t_user (userName, createTime) values (?, ?)
Hibernate: insert into t_user (userName, createTime) values (?, ?)
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_user set tagId=? where userID=?
Hibernate: update t_user set tagId=? where userID=?
?
?
?
代碼下載地址:
http://pan.baidu.com/s/1gdFt7ur
?
?
?
?
轉載于:https://www.cnblogs.com/rhythmK/p/3704133.html
總結
以上是生活随笔為你收集整理的Rhythmk 学习 Hibernate 05 - Hibernate 表间关系 [ManyToOne,OneToMany]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hibernate悲观锁/乐观锁
- 下一篇: sql 把多列内容合并