getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Object ret = null;
Transaction tx = session.beginTransaction();
try {
Criteria crit = session.createCriteria(Diary.class);
// 这行将对occasion进行唯一性合并
crit.setProjection(Projections.distinct(Projections.property("occasion")));
crit.createAlias("mission", "mission", Criteria.LEFT_JOIN);
crit.addOrder(Order.asc("occasion"));
ret = crit.list();
tx.commit();
} catch (Exception e) {
if (null != tx) {
tx.rollback();
}
e.printStackTrace();
if (e instanceof HibernateException)
throw (HibernateException) e;
if (e instanceof SQLException)
throw (SQLException) e;
}
return ret;
};
});
二:HQL Query(关于事务的管理同上。)
getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Recommendation doInHibernate(Session session)
throws HibernateException, SQLException {
Object ret = null;
Transaction tx = session.beginTransaction();
try {
// 当查询的结果集中只存在Recommendation对象时,distinct将结果集中的相同
// 对象合并成一个,如果left join fetch导致结果集中Recommendation对象与多个其它对象
// 造成查询结果的记录行不相同,则distinct无法对Recommendation对象合并。
String hql = "select distinct r from Recommendation r ";
hql += " left join fetch r.carries c left join fetch c.diary d ";
hql += " left join fetch r.prospectuses ps left join fetch ps.prospectus p ";
hql += " left join fetch p.policyTerms pt left join fetch pt.cover ";
hql += " where r.status=3503 or r.status=3504 ";
Query q = session.createQuery(hql);
Object lst = q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
tx.commit();
} catch (Exception e) {
if (null != tx) {
tx.rollback();
}
e.printStackTrace();
if (e instanceof HibernateException)
throw (HibernateException) e;
if (e instanceof SQLException)
throw (SQLException) e;
}
return lst;
}
});
分享到:
2012-04-18 16:20
浏览 3129
评论