1.创建项目,项目名称hibernatedemo9,目录结构如图所示
![QQ截图20170329151753.png Hibernate5-投影查询,分组查询,Query的List和Iterate_分组查询](https://s2.51cto.com/wyfs02/M00/8F/57/wKiom1jbX9aSGv0sAAAsNtP4Duc045.png?x-oss-process=image/resize,m_fixed,w_1184)
2.在项目中创建lib目录存储jar文件,目录结构如图所示
![QQ截图20170329151835.png Hibernate5-投影查询,分组查询,Query的List和Iterate_分组查询_02](https://s2.51cto.com/wyfs02/M00/8F/55/wKioL1jbX_2hHjG-AACKtSAR6X4933.png?x-oss-process=image/resize,m_fixed,w_1184)
3.在src目录中创建实体Bean Forum,包名(com.mycompany.demo.bean),如图所示
![QQ截图20170329151923.png Hibernate5-投影查询,分组查询,Query的List和Iterate_分组查询_03](https://s2.51cto.com/wyfs02/M01/8F/57/wKiom1jbYC7z_wQVAABEbKBchFQ498.png?x-oss-process=image/resize,m_fixed,w_1184)
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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fid;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public 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),如图所示
![QQ截图20170329152036.png Hibernate5-投影查询,分组查询,Query的List和Iterate_分组查询_04](https://s2.51cto.com/wyfs02/M01/8F/55/wKioL1jbYHji4nqyAABDO_3iYf4599.png?x-oss-process=image/resize,m_fixed,w_1184)
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),如图所示
![QQ截图20170329152358.png Hibernate5-投影查询,分组查询,Query的List和Iterate_投影查询_05](https://s2.51cto.com/wyfs02/M00/8F/55/wKioL1jbYUKgfbOlAAA-QRvpmn8085.png?x-oss-process=image/resize,m_fixed,w_1184)
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,如图所示
![QQ截图20170329152321.png Hibernate5-投影查询,分组查询,Query的List和Iterate_投影查询_06](https://s2.51cto.com/wyfs02/M02/8F/55/wKioL1jbYSGzICf5AAA4dwhVKIE239.png?x-oss-process=image/resize,m_fixed,w_1184)
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),目录结构如图所示
![QQ截图20170329152216.png Hibernate5-投影查询,分组查询,Query的List和Iterate_分组查询_07](https://s2.51cto.com/wyfs02/M01/8F/57/wKiom1jbYYDxYa5cAAA1zpL-j34055.png?x-oss-process=image/resize,m_fixed,w_1184)
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;
@Before
public void init(){
session = HbnUtil.getSession();
}
/*
* 投影查询-SQL
*/
@Test
public 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
*/
@Test
public 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
*/
@Test
public 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
*/
@Test
public 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
*/
@Test
public 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
*/
@Test
public 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.不使用缓存机制,每次查询都是从数据库获取
*/
@Test
public void testQueryForList(){
try {
session.beginTransaction();
String hql = "FROM Forum";
//会输出sql
List<Forum> forums = session.createQuery(hql).list();
for (Forum forum : forums) {
System.out.println(forum.getName());
}
//会输出sql
List<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问题
*/
@Test
public void testQueryForIterate(){
try {
session.beginTransaction();
String hql = "FROM Forum";
//会输出sql
Iterator<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问题方式
*/
@Test
public void testNPlusOne(){
try {
session.beginTransaction();
String hql = "FROM Forum";
//输出查询sql
List<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();
}
}
}
![QQ截图20170324102905.png Hibernate5-投影查询,分组查询,Query的List和Iterate_投影查询_08](https://s2.51cto.com/wyfs02/M01/8F/55/wKioL1jbYbGSgGh_AABwCKMO5XE044.png?x-oss-process=image/resize,m_fixed,w_1184)