测试了常用的一些HQL查询方法,具体HQL的强大可以参考:

http://docs.jboss.org/hibernate/orm/3.5/reference/zh-CN/html/queryhql.html#queryhql-casesensitivity


Java Beans:

package com.my.bean;

import java.util.Date;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table; @Entity
@Table(name="user")
public class User {
@Id @GeneratedValue @Column(name="user_id", nullable=false)
private long userID; @Column(name="user_name", length=100, nullable=false)
private String userName; @Column(name="create_time", nullable=false)
private Date createTime; @OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private Set<UserCard> cards; public long getUserID() {
return userID;
} public void setUserID(long userID) {
this.userID = userID;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public Set<UserCard> getCards() {
return cards;
} public void setCards(Set<UserCard> cards) {
this.cards = cards;
}
}
package com.my.bean;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table; @Entity
@Table(name="user_card")
public class UserCard {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="card_id")
private long cardID; @Column(name="card_name")
private String cardName; @ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="user_id")
private User user; public long getCardID() {
return cardID;
}
public void setCardID(long cardID) {
this.cardID = cardID;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

一些DTO的Java Beans:

package com.my.bean.dto;

public class GroupByTemp {
private long sumUser;
private long userID; public long getSumUser() {
return sumUser;
}
public void setSumUser(long sumUser) {
this.sumUser = sumUser;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
} /**
* @param sumUser
* @param userID
*/
public GroupByTemp(long sumUser, long userID) {
this.sumUser = sumUser;
this.userID = userID;
}
}
package com.my.bean.dto;

import java.math.BigInteger;
import java.util.Date; public class UserSQLTemp {
private BigInteger userID;
private Date createTime;
private String userName;
public BigInteger getUserID() {
return userID;
}
public void setUserID(BigInteger userID) {
this.userID = userID;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
package com.my.bean.dto;

public class UserTemp {
private long userID;
private String userName;
private String cardName; public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
} public UserTemp(long userID, String userName, String cardName) {
super();
this.userID = userID;
this.userName = userName;
this.cardName = cardName;
}
}

测试:

package com.my.init;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers; import com.my.bean.User;
import com.my.bean.UserCard;
import com.my.bean.dto.GroupByTemp;
import com.my.bean.dto.UserSQLTemp;
import com.my.bean.dto.UserTemp;
import com.my.dao.util.HibernateUtil; public class Test { @SuppressWarnings({ "unchecked" })
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction(); try {
// ----------------------------------------------------
// Select all data
// ----------------------------------------------------
String hql = "FROM User AS U ORDER BY U.createTime DESC";
Query query = session.createQuery(hql);
List<User> users = query.list();
for (User user : users) {
System.out.println("User:" + user.getUserName());
System.out.println("Card size:" + user.getCards().size());
for (UserCard c : user.getCards()) {
System.out.println("Card:" + c.getCardName());
}
} // ----------------------------------------------------
// Select all user name
// ----------------------------------------------------
hql = "SELECT U.userName FROM User AS U";
query = session.createQuery(hql);
List<String> userNames = query.list();
for (String item : userNames) {
System.out.println("Name:" + item);
} // ----------------------------------------------------
// Where
// ----------------------------------------------------
hql = "FROM User AS U WHERE U.userID=:userID";
query = session.createQuery(hql);
query.setParameter("userID", (long) 1);
users = query.list();
for (User user : users) {
System.out.println("User:" + user.getUserName());
} // ----------------------------------------------------
// Other fields, DTO
// ----------------------------------------------------
hql = "SELECT new com.my.bean.dto.UserTemp(U.userID, U.userName, C.cardName)"
+ " FROM User AS U, UserCard AS C"
+ " WHERE U.userID=:userID";
query = session.createQuery(hql);
query.setParameter("userID", (long) 2);
List<UserTemp> temps = query.list();
for (UserTemp item : temps) {
System.out.println("User name:" + item.getUserName()
+ "\tCard name:" + item.getCardName());
} // ----------------------------------------------------
// Group by
// ----------------------------------------------------
hql = "SELECT new com.my.bean.dto.GroupByTemp(SUM(C.user.userID), C.user.userID) FROM UserCard AS C GROUP BY C.cardName";
query = session.createQuery(hql);
List<GroupByTemp> results = query.list();
for (GroupByTemp item : results) {
System.out.println("UserID:" + item.getUserID() + "\tSum:"
+ item.getSumUser());
} // ----------------------------------------------------
// Count
// ----------------------------------------------------
hql = "SELECT COUNT(*) FROM User";
query = session.createQuery(hql);
long count = (long) query.uniqueResult();
System.out.println("Total:" + count); // ----------------------------------------------------
// SQL
// ----------------------------------------------------
String sql = "SELECT user_id AS userID, user_name AS userName, create_time AS createTime FROM user";
query = session.createSQLQuery(sql).setResultTransformer(
Transformers.aliasToBean(UserSQLTemp.class));
List<UserSQLTemp> usersTemp = query.list();
for (UserSQLTemp item : usersTemp) {
System.out.println("UserID:" + item.getUserID()
+ "\tUser name:" + item.getUserName());
} // ----------------------------------------------------
// Left join
// ----------------------------------------------------
hql = "SELECT U FROM User U LEFT JOIN U.cards C WITH C.cardID=:cardID WHERE U.userName=:userName";
query = session.createQuery(hql);
query.setLong("cardID", 1);
query.setString("userName", "Robin");
users = query.list();
for (User user : users) {
System.out.println("User ID:" + user.getUserID()
+ "\tUser name:" + user.getUserName());
} // ----------------------------------------------------
// Top N records
// ----------------------------------------------------
hql = "SELECT U FROM User AS U";
query = session.createQuery(hql).setMaxResults(1);
users = query.list();
for (User user : users) {
System.out.println("User name:" + user.getUserName());
} // ----------------------------------------------------
// Like
// ----------------------------------------------------
hql = "SELECT U FROM User AS U WHERE U.userName LIKE :userName";
query = session.createQuery(hql);
query.setString("userName", "%m%");
users = query.list();
for (User user : users) {
System.out.println("User name:" + user.getUserName());
} // ----------------------------------------------------
// Paging, set First result and Max result
// ----------------------------------------------------
hql = "SELECT U FROM User AS U";
query = session.createQuery(hql).setFirstResult(1).setMaxResults(1);
users = query.list();
for (User user : users) {
System.out.println("User name:" + user.getUserName());
} // ----------------------------------------------------
// IN
// ----------------------------------------------------
hql = "SELECT U FROM User AS U WHERE U.userID IN (:userID)";
query = session.createQuery(hql);
Long[] userIDs = new Long[] { (long) 1, (long) 2 };
query.setParameterList("userID", userIDs);
users = query.list();
for (User user : users) {
System.out.println("User name:" + user.getUserName());
} // ----------------------------------------------------
// Sub search
// ----------------------------------------------------
hql = "SELECT U FROM User AS U WHERE U IN (SELECT C.user FROM UserCard AS C WHERE C.cardID=:cardID)";
query = session.createQuery(hql);
query.setLong("cardID", 1);
users = query.list();
for (User user : users) {
System.out.println("User name:" + user.getUserName());
} // ----------------------------------------------------
// Sub case
// ----------------------------------------------------
hql = "SELECT new com.my.bean.dto.UserTemp("
+ "U.userID, U.userName, (SELECT C.cardName FROM UserCard C WHERE C.cardID=:cardID)"
+ ") FROM User U";
query = session.createQuery(hql);
query.setLong("cardID", 1);
temps = query.list();
for (UserTemp item : temps) {
System.out.println("UserID:" + item.getUserID()
+ "\tUser name:" + item.getUserName() + "\tCard name:"
+ item.getCardName());
} tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} session.close();
} }

HQL中也可以使用SQL,见测试例子:SQL

(但这种方法不推荐使用,因为这样就破坏了OO设计,除非在逼不得已的情况下,比如那些最初没设计好数据库然后又要出复杂到恶心的报表时)

[Hibernate] - Query Select的更多相关文章

  1. Hibernate 查询:HQL查询(Hibernate Query Languge)

    HQL是一种面向对象的查询语言,其中没有表和字段的概念,只有类,对象和属性的概念. 使用HQL查询所有学生: public static void main(String[] args) { Sess ...

  2. hql(Hibernate Query Language)

    1.Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Language)查询提供了更加丰富的和灵活的查询特性,因此Hibernate ...

  3. HQL: The Hibernate Query Language

    Chapter 14. HQL: The Hibernate Query Language 14.1. Case Sensitivity 14.2. The from clause 14.3. Ass ...

  4. Hibernate Query Language查询:

    Hibernate Query Language查询: Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Language)查询提供 ...

  5. HQL(Hibernate Query Language)

    1. NativeSQL > HQL > EJB QL(JP QL 1.0) > QBC(Query By Criteria) > QBE(Query By Example)2 ...

  6. 关于SubSonic3.0插件使用SubSonic.Query.Select查询时,字段类型为tinyint时列丢失问题的Bug修复

    下午在写代码时,突然发现一个列名为Enable的字段怎么也查询不出来,开始以为可能这个名称是关键字,所以给过滤掉了,所以就将名称修改为IsEnable,问题还是一样......将名称又改为IsEnab ...

  7. 为SubSonic3.0的查询(SubSonic.Query.Select和存储过程)添加更多的执行功能

    在使用SubSonic3.0的查询功能时,会发现想通过执行返回我们想要的数据,切没有相关的功能,比如说:SubSonic.Query.Select,在使用查询时没有返回DataSet或DataTabl ...

  8. Event filter with query "SELECT * FROM __InstanceModi

    Event filter with query "SELECT * FROM __InstanceModi     问题描述: Details -Event filter with quer ...

  9. Hibernate - Query简易

    package cn.demo; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; im ...

随机推荐

  1. caffe编译关于imread问题的解决

    change Makefile: LIBRARIES += glog gflags protobuf leveldb snappy \ lmdb boost_system hdf5_hl hdf5 m ...

  2. 104. Maximum Depth of Binary Tree

    Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...

  3. linux权限管理_ACL权限

    一.什么是ACL权限 ACL是Access Control List(访问控制列表)的缩写,主要的目的是在提供传统的owner,group,others的read,write,execute权限之外的 ...

  4. Codeforces Round #121 (Div. 2)

    A. Funky Numbers 记\(a \le b\),枚举\(a\)即可. B. Walking in the Rain 二分时间,然后\(dp(i)\)表示是否能从1到达i. C. Dynas ...

  5. Vue.js相关知识3-路由

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  6. Win10 EPLAN新建项目出现“一个内部错误的解决方法”

    [环境] Win10 64bits,EPLAN 2.4 64bits. [表现] 新建项目的时候出现"一个内部错误"的提示,然后软件卡死. [解决方案] 计算机管理--服务--EP ...

  7. makefile基础实例讲解 分类: C/C++ 2015-03-16 10:11 66人阅读 评论(0) 收藏

    一.makefile简介 定义:makefile定义了软件开发过程中,项目工程编译链.接接的方法和规则. 产生:由IDE自动生成或者开发者手动书写. 作用:Unix(MAC OS.Solars)和Li ...

  8. strlen() 函数

    strlen() 函数通常用来计算字符串的长度,但是今天突然发现个奇怪的现象. 如下所示: #include <stdio.h> #include <stdlib.h> #in ...

  9. dump java

    http://www.gamlor.info/wordpress/2011/09/visualvm/ https://visualvm.java.net/zh_CN/gettingstarted.ht ...

  10. PHP- 深入PHP、Redis连接

    pconnect, phpredis中用于client连接server的api. The connection will not be closed on close or end of reques ...