hibernate 命名查询
配置方式:
static List namedQuery(int id) {
Session s = HibernateUtil.getSession();
Query q = s.getNamedQuery("getUserById");
q.setInteger("id", id);
return q.list();
}
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sy.vo.User" table="user" catalog="news">
</class>
<!-- 命名查询:定义查询条件 -->
<query name="getUserById">
<![CDATA[from User where id=:id]]>
</query>
<!-- 命名查询中使用sql,不推荐使用,影响跨数据库
<sql-query name="getUserById2">
<![CDATA[select * from User where ]]>
</sql-query> -->
</hibernate-mapping>
标注方式:
标注方式是我们项目中用到的
,@Entity
@NamedQueries( {
@NamedQuery(name="Trade.findTotalPaymentAndBuyerNum",
query = "select sum(payment),count(distinct t.buyerNick),sum(t.postFee),sum(t.num) from Trade t where t.payTime >= :start and t.payTime < :end and t.sellerNick = :sellerNick"),
@NamedQuery(name="Trade.findCreatedPayments",
query = "select sum(payment),count(distinct t.buyerNick),sum(t.num) from Trade t where t.created >= :start and t.created < :end and t.sellerNick = :sellerNick")})
public class Trade {
。。。。
}
放在了类的前面,可以多个,有name跟query两个属性,而且query里面已经有了‘:start’这样的可以传递参数的。
其中一个Service的实现里面可以这样用:
public Object[] getTotalPaymentAndBuyerNum(String sellerNick, Date start, Date end) {
Map<String, Object> queryParams = new HashMap<String, Object>();
queryParams.put("sellerNick", sellerNick);
queryParams.put("start", start);
queryParams.put("end", end);
List list = genericDao.findByNamedQuery("Trade.findTotalPaymentAndBuyerNum", queryParams);
Object[] o = (Object[]) list.get(0);
return o;
}
genericDao的实现是继承了HibernateDaoSupport的:
public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
String[] params = new String[queryParams.size()];
Object[] values = new Object[queryParams.size()];
int index = 0;
Iterator<String> i = queryParams.keySet().iterator();
while (i.hasNext()) {
String key = i.next();
params[index] = key;
values[index++] = queryParams.get(key);
}
return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, params, values);
}
适用情况:万能方法,有点像ibatis轻量级框架的操作,方便维护。 缺点:不面向对象。基于hql和sql,有一定缺陷,第二种标注方式更简单易用,最主要是扩展性很强的,推荐用第二种方式方便开发。
转自http://blog.163.com/ksm19870304@126/blog/static/374552332011993942391/