標籤:hibernate5-1對多(1:n)-fetch="select"-lazy="false"
1.建立項目,項目名稱hibernatedemo23,目錄結構
650) this.width=650;" src="https://s5.51cto.com/wyfs02/M00/8F/88/wKiom1jkS66ixaaQAAAhKCFsVQ8175.png-wh_500x0-wm_3-wmp_4-s_1548641453.png" title="QQ20170405094219.png" alt="wKiom1jkS66ixaaQAAAhKCFsVQ8175.png-wh_50" />
2.在項目中建立lib目錄存放jar檔案,目錄結構
650) this.width=650;" src="https://s1.51cto.com/wyfs02/M01/8F/88/wKiom1jkS8-y93GzAABa1keXcbc982.png-wh_500x0-wm_3-wmp_4-s_1485382156.png" title="QQ20170405094250.png" alt="wKiom1jkS8-y93GzAABa1keXcbc982.png-wh_50" />
3.在src目錄中建立實體類Forum,包名(com.mycompany.demo.bean),
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M01/8F/85/wKioL1jkS_fhAu8bAAA3p7x3VWY877.png-wh_500x0-wm_3-wmp_4-s_1903337236.png" title="QQ20170405094331.png" alt="wKioL1jkS_fhAu8bAAA3p7x3VWY877.png-wh_50" />
4.實體類Forum的內容如下
package com.mycompany.demo.bean;import java.util.Set;public class Forum {private int fid;private String name;private Set<ForumPost> forumPosts;public int getFid() {return fid;}public void setFid(int fid) {this.fid = fid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<ForumPost> getForumPosts() {return forumPosts;}public void setForumPosts(Set<ForumPost> forumPosts) {this.forumPosts = forumPosts;}}
5.在src目錄中建立實體類Forum的對應檔Forum.hbm.xml,包名(com.mycompany.demo.bean),
650) this.width=650;" src="https://s4.51cto.com/wyfs02/M02/8F/85/wKioL1jkTEGC6w7GAAA801ZzDBA497.png-wh_500x0-wm_3-wmp_4-s_3593463686.png" title="QQ20170405094443.png" alt="wKioL1jkTEGC6w7GAAA801ZzDBA497.png-wh_50" />
6.對應檔Forum.hbm.xml的內容如下
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!--package:指定<class/>所在的包 --><hibernate-mapping package="com.mycompany.demo.bean"><!--name:類名table:表名 catalog:資料庫名稱,預設為hibernate.cfg.xml中配置的資料庫名稱 --> <class name="Forum" table="forum"> <meta attribute="class-description"> This class contains the forum detail. </meta> <!-- name:屬性名稱 colum:列名 --> <id name="fid" type="int" column="fid"> <!-- increment:hibernate維護主索引值 identity:資料庫自增長 sequence:序列 native:根據不同的資料庫選擇建置原則 uuid:通過UUID演算法產生,實際使用較多 assigned:手工設定 --> <generator class="native"/> </id> <!-- length:位元組長度 type:欄位類型,支援java和hibernate類型 not-null:非空約束 unique:唯一性限制式 --> <property name="name" column="name" /> <!-- lazy: false:直接載入 true:消極式載入 extra:特別消極式載入 fetch join:迫切左外串連 select:普通select查詢 subselect :子查詢方式 --> <set name="forumPosts" cascade="all" fetch="select" lazy="false"> <key column="fid"/> <one-to-many class="ForumPost"/> </set> </class></hibernate-mapping>
7.在src目錄中建立實體類ForumPost,包名(com.mycompany.demo.bean),
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M00/8F/85/wKioL1jkTJPDqXczAAA81Nah5dc291.png-wh_500x0-wm_3-wmp_4-s_886669193.png" title="QQ20170405094607.png" alt="wKioL1jkTJPDqXczAAA81Nah5dc291.png-wh_50" />
8.實體類ForumPost的內容如下
package com.mycompany.demo.bean;public class ForumPost {private int pid;private String subject;private Forum forum;public int getPid() {return pid;}public void setPid(int pid) {this.pid = pid;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public Forum getForum() {return forum;}public void setForum(Forum forum) {this.forum = forum;}}
9.在src目錄中建立實體類ForumPost的對應檔ForumPost.hbm.xml,包名(com.mycompany.demo.bean),
650) this.width=650;" src="https://s1.51cto.com/wyfs02/M01/8F/88/wKiom1jkTaWAt1ShAAA8IqDUsGs776.png-wh_500x0-wm_3-wmp_4-s_2146149678.png" title="QQ20170405095041.png" alt="wKiom1jkTaWAt1ShAAA8IqDUsGs776.png-wh_50" />
10.對應檔ForumPost.hbm.xml的內容如下
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!--package:指定<class/>所在的包 --><hibernate-mapping package="com.mycompany.demo.bean"><!--name:類名table:表名 catalog:資料庫名稱,預設為hibernate.cfg.xml中配置的資料庫名稱 --> <class name="ForumPost" table="forumpost"> <meta attribute="class-description"> This class contains the forumpost detail. </meta> <!-- name:屬性名稱 colum:列名 --> <id name="pid" type="int" column="pid"> <!-- increment:hibernate維護主索引值 identity:資料庫自增長 sequence:序列 native:根據不同的資料庫選擇建置原則 uuid:通過UUID演算法產生,實際使用較多 assigned:手工設定 --> <generator class="native"/> </id> <!-- length:位元組長度 type:欄位類型,支援java和hibernate類型 not-null:非空約束 unique:唯一性限制式 --> <property name="subject" column="subject" type="string" length="50" not-null="true" unique="false"/> <!-- name:關聯屬性 column:關聯屬性在資料庫對應的欄位 class:關聯屬性所對應的類型 --> <many-to-one name="forum" class="Forum" column="fid"/> </class> <query name="queryAll">from Forum f left outer join fetch f.forumPosts</query></hibernate-mapping>
11.在src目錄中建立工具類 HbnUtil,包名(com.mycompany.demo.util),
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M01/8F/85/wKioL1jkTeaCE-VtAAAwVr4kmB0768.png-wh_500x0-wm_3-wmp_4-s_2949916934.png" title="QQ20170405095146.png" alt="wKioL1jkTeaCE-VtAAAwVr4kmB0768.png-wh_50" />
12.工具類 HbnUtil的內容如下
package com.mycompany.demo.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HbnUtil {private static SessionFactory sessionFactory;public static Session getSession(){if(sessionFactory == null || sessionFactory.isClosed()){sessionFactory = new Configuration().configure().buildSessionFactory();}return sessionFactory.getCurrentSession();}}
13.在src目錄中建立Hibernate的設定檔hibernate.cfg.xml,
650) this.width=650;" src="https://s3.51cto.com/wyfs02/M02/8F/88/wKiom1jkThmQxBztAAAstaUbBBA781.png-wh_500x0-wm_3-wmp_4-s_2581509415.png" title="QQ20170405095237.png" alt="wKiom1jkThmQxBztAAAstaUbBBA781.png-wh_50" />
14.Hibernate的設定檔hibernate.cfg.xml的內容如下
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- 方言,可以從Hibernate核心jar(hibernate-core-x.x.x.Finall.jar) 檔案中的or.hibernate.dialect包中找到相應的類,類的全名就是 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 驅動 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 資料庫連接地址 --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <!-- 使用者名稱 --> <property name="hibernate.connection.username"> root </property> <!-- 密碼 --> <property name="hibernate.connection.password"></property> <!-- create:每次都新建立,如果存在就刪除 create-drop:建立新表,sessionFactory關閉,表會刪除 update :表欄位增加,會同步,欄位減少不同步,資料改變會同步修改 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 輸出sql --> <property name="hibernate.show_sql">true</property> <!-- 格式化sql --> <property name="hibernate.format_sql">true</property> <!-- 事務環境一個線程對一個事務 thread:本地事務環境 jta:分散式交易環境 SpringSessionContext:用於ssh整合 --> <property name="hibernate.current_session_context_class">thread</property> <!-- 使用c3p0資料來源 --> <property name="hibernate.connection.provider_class"> org.hibernate.c3p0.internal.C3P0ConnectionProvider</property> <!-- List of XML mapping files --> <mapping resource="com/mycompany/demo/bean/Forum.hbm.xml"/> <mapping resource="com/mycompany/demo/bean/ForumPost.hbm.xml"/></session-factory></hibernate-configuration>
15.在項目中建立test目錄存放測試檔案,檔案名稱TestApp,包名(com.mycompany.demo.bean),目錄結構
650) this.width=650;" src="https://s5.51cto.com/wyfs02/M02/8F/88/wKiom1jkTmmi_cU3AAAqDqpX0b4910.png-wh_500x0-wm_3-wmp_4-s_2644524026.png" title="QQ20170405095357.png" alt="wKiom1jkTmmi_cU3AAAqDqpX0b4910.png-wh_50" />
16.TestApp測試類別的內容如下
package com.mycompany.demo.bean;import java.util.HashSet;import java.util.List;import java.util.Set;import org.hibernate.Criteria;import org.hibernate.Session;import org.hibernate.sql.JoinType;import org.junit.Before;import org.junit.Test;import com.mycompany.demo.util.HbnUtil;public class TestApp {private Session session;@Beforepublic void init(){session = HbnUtil.getSession();}/* * 一對多雙向關聯-添加 * 需要設定Forum.hbm.xml中的Set屬性為cascade="all" */@Testpublic void testOneToManyAdd(){try {session.beginTransaction();ForumPost forumPost1 = new ForumPost();forumPost1.setSubject("A");ForumPost forumPost2 = new ForumPost();forumPost2.setSubject("B");Set<ForumPost> forumPosts = new HashSet<ForumPost>();forumPosts.add(forumPost1);forumPosts.add(forumPost2);Forum forum = new Forum();forum.setName("foruma");forum.setForumPosts(forumPosts);session.save(forum);session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 一對多雙向關聯-fetch="select",lazy="false" */@Testpublic void testFetchForSelect(){try {session.beginTransaction();Forum forum = session.get(Forum.class, 10);Set<ForumPost> forumPosts = forum.getForumPosts();for (ForumPost forumPost : forumPosts) {System.out.println(forumPost.getSubject());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}}
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M02/8F/86/wKioL1jkTouTTRZ2AABwCKMO5XE547.png-wh_500x0-wm_3-wmp_4-s_2991448208.png" title="QQ20170324102905.png" alt="wKioL1jkTouTTRZ2AABwCKMO5XE547.png-wh_50" />
本文出自 “素顏” 部落格,謝絕轉載!
Hibernate5-1對多(1:n)-fetch="select"-lazy="false"