1.hibernate:查找总共多少条记录
Long count = (Long)session.createQuery("select count(*) from Student").uniqueResult();
2.分组查询多少条记录并输出
List students =session.createQuery("select c.name, count(s) from Student s join s.classes c " +
"group by c.name order by c.name").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + ", " + obj[1]);
}
3.这样的方式(session.createSQLQuery("..."))要以数组形式输出
List students = session.createSQLQuery("select * from t_student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
4.单一属性查询
//返回结果集属性列表,元素类型和实体类中相应的属性类型一致
List students = session.createQuery("select name from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
String name = (String)iter.next();
System.out.println(name);
}
5.多个属性查询
//查询多个属性,其集合元素是对象数组
//数组元素的类型和对应的属性在实体类中的类型一致
//数组的长度取决与select中属性的个数
List students = session.createQuery("select id, name from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
6.实体查询1(以Student对象为例)
//如果认为返回数组不够对象化,可以采用hql动态实例化Student对象
//此时list中为Student对象集合
List students = session.createQuery("select new Student(id, name) from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getId() + "," + student.getName());
}
7.实体对象查询2
/**
* 采用list查询发出一条查询语句,取得Student对象数据、
*
* Hibernate: select student0_.id as id1_, student0_.name as name1_,
* student0_.createTime as createTime1_, student0_.classesid as classesid1_
* from t_student student0_
*
*/
List students = session.createQuery("from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
8.实体对象查询3
//返回Student对象的集合
//使用select查询实体对象,必须采用别名
List students = session.createQuery("select s from Student as s").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
//不支持select * from .....这样的查询语句
List students = session.createQuery("select * from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
9.N+1问题
/**
* 出现N+1问题
*
* 1:发出查询id列表的sql
* Hibernate: select student0_.id as col_0_0_ from t_student student0_
*
* N:在依次发出根据id查询Student对象的sql
* Hibernate: select student0_.id as id1_0_, student0_.name as name1_0_,
* student0_.createTime as createTime1_0_, student0_.classesid as classesid1_0_
* from t_student student0_ where student0_.id=?
*
*/
Iterator iter = session.createQuery("from Student").iterate();
while(iter.hasNext()) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
10.不会出现N+1问题
try {
session = HibernateUtils.getSession();
session.beginTransaction();
List students = session.createQuery("from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
System.out.println("---------------------------------------------");
/**
* 不会出现N+1问题
*
* 因为list操作已经将Student对象放到了一级缓存中,所以再次使用iterate操作的时候
* 它首先发出一条查询id列表的sql,在根据id到缓存中去数据,只有在缓存中找不到相应的
* 数据时,才会发出sql到数据库中查询
*
*/
Iterator iter = session.createQuery("from Student").iterate();
while(iter.hasNext()) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
11.不利用缓存,再次发出SQL语句
try {
session = HibernateUtils.getSession();
session.beginTransaction();
List students = session.createQuery("from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
System.out.println("---------------------------------------------");
/**
* 再次发出查询sql
*
* 在默认情况下list每次都会向数据库发出查询对象的sql,除非配置查询缓存,所以下面的list操作
* 虽然在一级缓存中已经有了对象数据,但list默认情况下不会利用缓存,而再次发出sql
*
* 默认情况下,list会向缓存中放入数据,但不会利用数据
*
*/
students = session.createQuery("from Student").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
12.条件查询
(1)使用?
//可以拼字符串
List students = session.createQuery("select s.id, s.name from Student s where s.name like '%1%'").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
也可以这样写:
List students = session.createQuery("select s.id,s.name from Student s where s.name like ?)
.setPremeter(0,"%"+condition+"%")
.list();
(2)使用 :参数
//使用 :参数名称 的方式传递参数值
List students = session.createQuery("select s.id, s.name from Student s where s.name like :myname")
.setParameter("myname", "%1%")
.list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
(3)支持in
//支持in,需要使用setParameterList进行参数传递
List students = session.createQuery("select s.id, s.name from Student s where s.id in(:myids)")
.setParameterList("myids", new Object[]{1, 2, 3, 4, 5})
.list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
(4)带有时间参数
//查询2008年2月创建的学生
List students = session.createQuery("select s.id, s.name from Student s where date_format(s.createTime, '%Y-%m')=?")
.setParameter(0, "2008-02")
.list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
(5)
session.beginTransaction();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//查询2008-01-10到2008-02-15创建的学生
List students = session.createQuery("select s.id, s.name from Student s where s.createTime between ? and ?")
.setParameter(0, sdf.parse("2008-01-10 00:00:00"))
.setParameter(1, sdf.parse("2008-02-15 23:59:59"))
.list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
session.getTransaction().commit();
13.分页
session.beginTransaction();
List students = session.createQuery("from Student")
.setFirstResult(1)
.setMaxResults(2)
.list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Student student = (Student)iter.next();
System.out.println(student.getName());
}
session.getTransaction().commit();
14.链接查询
(1) List students = session.createQuery("select c.name, s.name from Student s inner join s.classes c").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
(2) List students = session.createQuery("select c.name, s.name from Classes c left join c.students s").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
(3) List students = session.createQuery("select c.name, s.name from Classes c right join c.students s").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
15.随机日期
student.setCreateTime(randomDate("2008-01-01","2008-03-01"));
/**
* 获取随机日期
* @param beginDate 起始日期,格式为:yyyy-MM-dd
* @param endDate 结束日期,格式为:yyyy-MM-dd
* @return
*/
private static Date randomDate(String beginDate,String endDate){
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date start = format.parse(beginDate);
Date end = format.parse(endDate);
if(start.getTime() >= end.getTime()){
return null;
}
long date = random(start.getTime(),end.getTime());
return new Date(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static long random(long begin,long end){
long rtn = begin + (long)(Math.random() * (end - begin));
if(rtn == begin || rtn == end){
return random(begin,end);
}
return rtn;
}
16.DML风格
/**
* DML风格的操作
* @author Administrator
*
*/
public class DMLQueryTest extends TestCase {
public void testQuery1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
session.createQuery("update Student s set s.name=? where s.id < ?")
.setParameter(0, "李四")
.setParameter(1, 5)
.executeUpdate();
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtils.closeSession(session);
}
}
}