標籤:hibernate5-投影查詢 分組查詢 query的list和iterate
1.建立項目,項目名稱hibernatedemo9,目錄結構
650) this.width=650;" src="https://s4.51cto.com/wyfs02/M00/8F/57/wKiom1jbX9aSGv0sAAAsNtP4Duc045.png-wh_500x0-wm_3-wmp_4-s_3682325420.png" title="QQ20170329151753.png" alt="wKiom1jbX9aSGv0sAAAsNtP4Duc045.png-wh_50" />
2.在項目中建立lib目錄存放jar檔案,目錄結構
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M00/8F/55/wKioL1jbX_2hHjG-AACKtSAR6X4933.png-wh_500x0-wm_3-wmp_4-s_1607087323.png" title="QQ20170329151835.png" alt="wKioL1jbX_2hHjG-AACKtSAR6X4933.png-wh_50" />
3.在src目錄中建立實體Bean Forum,包名(com.mycompany.demo.bean),
650) this.width=650;" src="https://s2.51cto.com/wyfs02/M01/8F/57/wKiom1jbYC7z_wQVAABEbKBchFQ498.png-wh_500x0-wm_3-wmp_4-s_2051905769.png" title="QQ20170329151923.png" alt="wKiom1jbYC7z_wQVAABEbKBchFQ498.png-wh_50" />
4.實體Bean Forum的內容如下
package com.mycompany.demo.bean;public class Forum {private int fid;private String name;private int isshow;public int getIsshow() {return isshow;}public void setIsshow(int isshow) {this.isshow = isshow;}public Forum() {super();}public Forum(String name) {super();this.name = name;}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;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + fid;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Forum other = (Forum) obj;if (fid != other.fid)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}
5.在src目錄中建立實體Bean Forum的對應檔Forum.hbm.xml,包名(com.mycompany.demo.bean),
650) this.width=650;" src="https://s3.51cto.com/wyfs02/M01/8F/55/wKioL1jbYHji4nqyAABDO_3iYf4599.png-wh_500x0-wm_3-wmp_4-s_3388242157.png" title="QQ20170329152036.png" alt="wKioL1jbYHji4nqyAABDO_3iYf4599.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="hnsq_forum" catalog="b_shequ_two"> <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" type="string" length="50" not-null="true" unique="false"/> <property name="isshow" column="isshow"></property> </class></hibernate-mapping>
7.在src目錄中建立工具類 HbnUtil,包名(com.mycompany.demo.util),
650) this.width=650;" src="https://s3.51cto.com/wyfs02/M00/8F/55/wKioL1jbYUKgfbOlAAA-QRvpmn8085.png-wh_500x0-wm_3-wmp_4-s_2140923936.png" title="QQ20170329152358.png" alt="wKioL1jbYUKgfbOlAAA-QRvpmn8085.png-wh_50" />
8.工具類 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();}}
9.在src目錄中建立Hibernate的設定檔hibernate.cfg.xml,
650) this.width=650;" src="https://s3.51cto.com/wyfs02/M02/8F/55/wKioL1jbYSGzICf5AAA4dwhVKIE239.png-wh_500x0-wm_3-wmp_4-s_2910669729.png" title="QQ20170329152321.png" alt="wKioL1jbYSGzICf5AAA4dwhVKIE239.png-wh_50" />
10.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/b_shequ_two</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"/></session-factory></hibernate-configuration>
11.在項目中建立test目錄存放測試檔案,檔案名稱ManageForum,包名(com.mycompany.demo.bean),目錄結構
650) this.width=650;" src="https://s1.51cto.com/wyfs02/M01/8F/57/wKiom1jbYYDxYa5cAAA1zpL-j34055.png-wh_500x0-wm_3-wmp_4-s_2172248738.png" title="QQ20170329152216.png" alt="wKiom1jbYYDxYa5cAAA1zpL-j34055.png-wh_50" />
12.ManageForum測試類別的內容如下
package com.mycompany.demo.bean;import java.util.Iterator;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.criterion.ProjectionList;import org.hibernate.criterion.Projections;import org.hibernate.transform.Transformers;import org.junit.Before;import org.junit.Test;import com.mycompany.demo.util.HbnUtil;public class ManageForum {private Session session;@Beforepublic void init(){session = HbnUtil.getSession();}/* * 投影查詢-SQL */@Testpublic void testProjectionSQL(){try {session.beginTransaction();String sql = "SELECT fid,name FROM hnsq_forum";List<Forum> forums = session.createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(Forum.class)).list();for (Forum forum : forums) {System.out.println(forum.getName());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 投影查詢-HQL */@Testpublic void testProjectionHQL(){try {session.beginTransaction();String sql = "SELECT new Forum(name) FROM Forum";List<Forum> forums = session.createQuery(sql).list();for (Forum forum : forums) {System.out.println(forum.getName());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 投影查詢-QBC */@Testpublic void testProjectionQBC(){try {session.beginTransaction();ProjectionList projections = Projections.projectionList().add(Projections.alias(Projections.property("name"), "name")).add(Projections.alias(Projections.property("fid"), "fid"));List<Forum> forums = session.createCriteria(Forum.class).setProjection(projections).setResultTransformer(Transformers.aliasToBean(Forum.class)).list();for (Forum forum : forums) {System.out.println(forum.getFid() +"=>" + forum.getName());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 分組查詢-SQL */@Testpublic void testGrounpForSQL(){try {session.beginTransaction();String sql = "SELECT isshow FROM hnsq_forum GROUP BY isshow";List<Boolean> lists = session.createSQLQuery(sql).list();for (Boolean isshow : lists) {System.out.println(isshow);}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 分組查詢-HQL */@Testpublic void testGrounpForHQL(){try {session.beginTransaction();String sql = "SELECT isshow FROM Forum GROUP BY isshow";List<Object> lists = session.createQuery(sql).list();for (Object isshow : lists) {System.out.println(isshow);}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 分組查詢-QBC */@Testpublic void testGrounpForQBC(){try {session.beginTransaction();List<Object> lists = session.createCriteria(Forum.class).setProjection(Projections.groupProperty("isshow")).list();for (Object isshow : lists) {System.out.println(isshow);}session.getTransaction().commit();} catch (HibernateException e) {session.getTransaction().rollback();e.printStackTrace();}}/* * Query的list查詢 * 1.一次性將所有合格記錄查詢出來 * 2.不使用緩衝機制,每次查詢都是從資料庫擷取 */@Testpublic void testQueryForList(){try {session.beginTransaction();String hql = "FROM Forum";//會輸出sqlList<Forum> forums = session.createQuery(hql).list();for (Forum forum : forums) {System.out.println(forum.getName());}//會輸出sqlList<Forum> forums2 = session.createQuery(hql).list();for (Forum forum : forums2) {System.out.println(forum.getName());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * Query的iterate查詢 * 1.查詢出所有合格記錄的id,然後再根據id查詢出記錄的具體內容 * 2.使用緩衝機制,先從緩衝讀取,如果沒有再從資料庫中讀取資料 * 3.會產生N+1問題 */@Testpublic void testQueryForIterate(){try {session.beginTransaction();String hql = "FROM Forum";//會輸出sqlIterator<Forum> forums = session.createQuery(hql).iterate();while(forums.hasNext()){System.out.println(forums.next().getName());}//這裡會產生查詢id的sql,其他的具體記錄資訊根據id從緩衝中讀取資料Iterator<Forum> forums2 = session.createQuery(hql).iterate();while(forums2.hasNext()){System.out.println(forums2.next().getName());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}/* * 解決N+1問題方式 */@Testpublic void testNPlusOne(){try {session.beginTransaction();String hql = "FROM Forum";//輸出查詢sqlList<Forum> forums = session.createQuery(hql).list();for (Forum forum : forums) {System.out.println(forum.getName());}//這裡會產生查詢id的sql,其他的具體記錄資訊根據id從緩衝中讀取資料Iterator<Forum> forums2 = session.createQuery(hql).iterate();while(forums2.hasNext()){System.out.println(forums2.next().getName());}session.getTransaction().commit();} catch (Exception e) {session.getTransaction().rollback();e.printStackTrace();}}}
650) this.width=650;" src="https://s5.51cto.com/wyfs02/M01/8F/55/wKioL1jbYbGSgGh_AABwCKMO5XE044.png-wh_500x0-wm_3-wmp_4-s_3768817016.png" title="QQ20170324102905.png" alt="wKioL1jbYbGSgGh_AABwCKMO5XE044.png-wh_50" />
本文出自 “素顏” 部落格,謝絕轉載!
Hibernate5-投影查詢,分組查詢,Query的List和Iterate