本系列博客汇总在这里:Hibernate 汇总
一、HQL 查询源码工程文件为:hibernate4.3_10
HQL(Hibernate Query Language),hibernate 的专属语言,可以跨数据库,根据不同数据库方言翻译成不同 sql,跟 SQL 很相似。
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// 查询所有的user类的对象
// String hql = "from User";
String hql = "select u from User u";// hql中没有*的写法
// 根据hql语句创建查询对象
Query query = session.createQuery(hql);
// 查询列表
List<User> userList = query.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
/**
* 查询对象的属性
*/
@Test
public void testQuery2()
{
Session session = HibernateUtils.getSession();
try
{
// 查询所有的user类的对象
// String hql = "from User";
String hql = "select u.uname from User u";// hql中没有*的写法
// 根据hql语句创建查询对象
Query query = session.createQuery(hql);
// 查询列表
List<String> nameList = query.list();
for (String name : nameList)
{
System.out.println(name);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
/**
* 查询对象的多个属性
*/
@Test
public void testQuery3()
{
Session session = HibernateUtils.getSession();
try
{
// 查询所有的user类的对象
// String hql = "from User";
String hql = "select u.uname, u.gender from User u";// hql中没有*的写法
// 根据hql语句创建查询对象
Query query = session.createQuery(hql);
// 查询列表,多个属性的查询要使用Object[]来做接收
List<Object[]> objArrList = query.list();
for (Object[] objArr : objArrList)
{
System.out.println("姓名:" + objArr[0] + " 性别:" + objArr[1]);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
/**
* 分页查询
*/
@Test
public void testQuery5()
{
Session session = HibernateUtils.getSession();
try
{
// 查询所有的user类的对象
// String hql = "from User";
String hql = "select u from User u";// hql中没有*的写法
// 根据hql语句创建查询对象
Query query = session.createQuery(hql);
// 从前台传递过来的是页码PageNo, startNum = (pageNo - 1)*pageSize
// 查询列表
List<User> userList = query.setFirstResult(5).setMaxResults(5)
.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery5()
{
Session session = HibernateUtils.getSession();
try
{
String hql = "select u from User u where u.gender = ? and u.uname = ?";// hql中没有*的写法
Query query = session.createQuery(hql);
// 设置第一个参数的值,和JDBC不同,预编译的索引从0开始
query.setParameter(0, 2);
query.setParameter(1, "任亮5");
List<User> userList = query.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery6()
{
Session session = HibernateUtils.getSession();
try
{
// 传参的语法 :[自定义名称]
String hql = "select u from User u where u.gender = :gender and u.uname = :uname";// hql中没有*的写法
Query query = session.createQuery(hql);
// 给自定义的参数赋值
query.setParameter("gender", 1);
query.setParameter("uname", "任亮8");
List<User> userList = query.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery5()
{
Session session = HibernateUtils.getSession();
try
{
// 查询记录数
// String hql = "select count(u.userId) from User u";
// 查询最大值
// String hql = "select max(u.userId) from User u";
// 查询最小值
// String hql = "select min(u.userId) from User u";
// 查询平均值
// String hql = "select avg(u.userId) from User u";
// 统计求和
String hql = "select sum(u.userId) from User u";
Query query = session.createQuery(hql);
// 查询唯一的结果
Object obj = query.uniqueResult();
System.out.println(obj);
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery6()
{
Session session = HibernateUtils.getSession();
try
{
// 统计求和
String hql = "select avg(u.salary), u.gender from User u group by u.gender having avg(u.salary) > 1400";
Query query = session.createQuery(hql);
// 查询唯一的结果
List<Object[]> objArrList = query.list();
for (Object[] objArr : objArrList)
{
System.out.println("平均工资:" + objArr[0] + " 性别:" + objArr[1]);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery7()
{
Session session = HibernateUtils.getSession();
try
{
// 我们可以创建一个业务Bean,在Bean提供有参数的构造器来接收sql返回的值,创建出对象语法 在select后面new
// com.rl.hiber.model.EmpBean(max(u.salary), u.gender)
String hql = "select new com.wyx.hiber.model.EmpBean(max(u.salary), u.gender) from User u group by u.gender having avg(u.salary) > 1400";
Query query = session.createQuery(hql);
// 查询唯一的结果
List<EmpBean> objArrList = query.list();
for (EmpBean objArr : objArrList)
{
System.out.println(objArr);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// 查询所有的user类的对象
// String hql = "from User";
String hql = "select u from User u order by u.salary desc";// hql中没有*的写法
// 根据hql语句创建查询对象
Query query = session.createQuery(hql);
// 查询列表
List<User> userList = query.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery2()
{
Session session = HibernateUtils.getSession();
try
{
// String hql =
// "select u from User u where u.uname like '%亮%'";//hql中没有*的写法
// 模糊查询和sql中的语法一致
String hql = "select u from User u where u.uname like '%宇_'";// hql中没有*的写法
// 根据hql语句创建查询对象
Query query = session.createQuery(hql);
// 查询列表
List<User> userList = query.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
package:指定当前映射文件的实体类model所在的包
-->
<hibernate-mapping package="com.wyx.hiber.model">
<!--
lazy:当前类是否使用延迟加载,默认是true使用,false不使用
-->
<class name="User" table="t_user">
<!-- id
是主键映射配置
-->
<id name="userId" column="user_id">
<!--
generator:主键的映射策略
-->
<generator class="native"></generator>
</id>
<property name="uname"></property>
<property name="salary"></property>
<property name="gender"></property>
<property name="birthday"></property>
</class>
<!--
query:定义hql语句
name:查询的名字,唯一
-->
<query name="getUserAll">
<![CDATA[
from User u where u.salary > :salary
]]>
</query>
</hibernate-mapping>
查询:
public void testQuery2()
{
Session session = HibernateUtils.getSession();
try
{
// 从映射文件中获得hql语句创建query对象
Query query = session.getNamedQuery("getUserAll");
query.setParameter("salary", 1500);
// 查询列表
List<User> userList = query.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
二、QBC 查询
QBC(Query By Criteria)是 hibernate 提供的一套查询 API,跨数据库。
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery2()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 获得具体要查询的属性
PropertyProjection pp = Projections.property("uname");
// 设置具体要查询的列
c.setProjection(pp);
// 查询User类对象的列表
List<String> unames = c.list();
for (String name : unames)
{
System.out.println(name);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery3()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 创建要查询的列的集合
ProjectionList pl = Projections.projectionList();
// 获得具体要查询的属性
PropertyProjection pp = Projections.property("uname");
PropertyProjection pp1 = Projections.property("gender");
// 把要查询的属性加入到集合中
pl.add(pp);
pl.add(pp1);
// 设置具体要查询的列
c.setProjection(pl);
// 查询User类对象的列表
List<Object[]> objArrList = c.list();
for (Object[] objArr : objArrList)
{
System.out.println("姓名:" + objArr[0] + " 性别:" + objArr[1]);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 设置要查询的项
c.setProjection(Projections.rowCount());
Object obj = c.uniqueResult();
System.out.println("总记录数:" + obj);
// 设置要查询薪水的最大值
c.setProjection(Projections.max("salary"));
Object obj1 = c.uniqueResult();
System.out.println("最高薪水:" + obj1);
// 设置要查询薪水的最小值
c.setProjection(Projections.min("salary"));
Object obj2 = c.uniqueResult();
System.out.println("最低薪水:" + obj2);
// 设置要查询薪水的平均值
c.setProjection(Projections.avg("salary"));
Object obj3 = c.uniqueResult();
System.out.println("平均薪水:" + obj3);
// 设置要查询薪水的平均值
c.setProjection(Projections.sum("salary"));
Object obj4 = c.uniqueResult();
System.out.println("员工薪水总和:" + obj4);
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery2()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 创建查询项的集合
ProjectionList pl = Projections.projectionList();
// 创建查询项
PropertyProjection pp = Projections.property("gender");
// 创建统计项
AggregateProjection ap = Projections.max("salary");
// 设置按着哪一项分组
PropertyProjection pp1 = Projections.groupProperty("gender");
// 把要查询的项加入到集合
pl.add(pp);
pl.add(ap);
pl.add(pp1);
// 把查询集合设置给qbc接口
c.setProjection(pl);
List<Object[]> objArrList = c.list();
for (Object[] objArr : objArrList)
{
System.out
.println("性别:" + objArr[0] + " 最高的工资是:" + objArr[1]);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 设置排序字段
c.addOrder(Order.desc("salary"));
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery2()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 设置排序字段
c.addOrder(Order.desc("salary"));
// 设置开始行号
c.setFirstResult(5);
// 设置每页记录数
c.setMaxResults(5);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
我们通过 Restrictions 来设置限定查询的条件。
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 创建查询条件
Criterion ct = Restrictions.eq("userId", 5);
// 把查询条件设置给QBC的查询接口
c.add(ct);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery3()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 创建查询条件,默认查询条件使用and来做连接
Criterion ct = Restrictions.gt("salary", 1500);
Criterion ct1 = Restrictions.lt("salary", 1800);
// 把查询条件设置给QBC的查询接口
c.add(ct);
c.add(ct1);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery4()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// 定义要查询的in的集合(也可以是数组)
Integer[] userIds = new Integer[] { 1, 2, 3 };
// 设置查询条件
Criterion ct = Restrictions.in("userId", userIds);
c.add(ct);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery5()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// and的条件的使用
Criterion ct = Restrictions.and(Restrictions.ge("salary", 1500),
Restrictions.eq("gender", 2));
c.add(ct);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery6()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// or的条件的使用
Criterion ct = Restrictions.or(Restrictions.ge("salary", 1800),
Restrictions.eq("gender", 1));
c.add(ct);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
public void testQuery7()
{
Session session = HibernateUtils.getSession();
try
{
// 创建qbc的查询接口的实现类
Criteria c = session.createCriteria(User.class);
// or的条件的使用,like的模糊查询like的第二个参数和sql语法一致,只是不需要单引号
Criterion ct = Restrictions.like("uname", "%宇%");
c.add(ct);
// 查询User类对象的列表
List<User> userList = c.list();
for (User user : userList)
{
System.out.println(user);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
三、SQL 查询
可以使用原生 sql 查询
public void testQuery1()
{
Session session = HibernateUtils.getSession();
try
{
// sql定义
String sql = "select uname, gender from t_user";
// 创建sql的查询接口的实现类
SQLQuery query = session.createSQLQuery(sql);
List<Object[]> objArrList = query.list();
for (Object[] objArr : objArrList)
{
System.out.println("姓名:" + objArr[0] + " 性别:" + objArr[1]);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
HibernateUtils.closeResource(session);
}
}
如有错误,欢迎指正!