一、HQL查询
HQL查询是一种针对对象的查询,根据对象的属性而不是数据库的字段来查询。常用语句有FROM,AS,SELECT,WHERE,
ORDER BY,GROUP BY,UPDATE,DELTE,INSERT等。支持相应的函数AVG(),count(),max(),
min(),sum()等。
例子:
String hql = "SELECT Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
List result = query.list();
二、标准查询
直接上例子:
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("age", 20));
cr.addOrder(Order.desc("name"));
cr.setProjection(Projections.max("salary"));
List results = cr.list();
其中Restrictions有eq,gt,lt,like,ilike,between,isNull,isNotNull,isEmpty,isNotEmpty等
其中Projections有rowCount,avg,countDistinct,max,min,sum等
三、原生sql
语法跟HQL差不多。有
1.标量查询
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List results = query.list();
2.实体查询
String sql = "SELECT * FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
List results = query.list();