hibernate 使用where 条件查询
public Department queryDepartmentById (int id) {
// 获得hibernate session
Session session = HibernateUtils.getSession();
// 获得事物
Transaction transaction = session.getTransaction();
try {
// 开启事物
transaction.begin();
// 获得CriteriaBuilder 用来创建CriteriaQuery
CriteriaBuilder builder = session.getCriteriaBuilder();
// 创建CriteriaQuery 参数为返回结果类型
CriteriaQuery<Department> criteria = builder.createQuery(Department.class);
// 返会查询表 参数类型为要查询的持久类
Root<Department> root = criteria.from(Department.class);
// 设置where条件
criteria.where(builder.equal(root.get("id"), id));
// 创建query 查询
Query<Department> query = session.createQuery(criteria);
// 返回结果
Department department = query.getSingleResult();
transaction.commit();
return department;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
}
return null;
}
hibernate criteria 统计查询
/**
* 查询部门总数
* 2018年10月11日
* @return 部门总数
*/
public Integer totalDepartment () {
Session session = HibernateUtils.getSession();
Transaction transaction = session.getTransaction();
try {
transaction.begin();
CriteriaBuilder builder = session.getCriteriaBuilder();
// 参数为查询的结果类型
CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
// 从什么表查询
Root<Department> root = criteria.from(Department.class);
// 就是sql select 之后的语句
criteria.select(builder.count(root));
// 使用query 实现查询
Query<Long> query = session.createQuery(criteria);
// 结果集
Long result = query.uniqueResult();
transaction.commit();
return result.intValue();
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
}
return null;
}