转:http://blog.csdn.net/u014223536/article/details/26453471
iabernate 中createQuery与createSQLQuery区别,使用经验
createQuery与createSQLQuery两者区别是:
前者用的hql语句进行查询,后者可以用sql语句查询
前者以hibernate生成的Bean为对象装入list返回
后者则是以对象数组进行存储
所以使用createSQLQuery有时候也想以hibernate生成的Bean为对象装入list返回
如下示例:
- @Override
- public List<Commodity> findCommodityByActyId(int activityId) {
- String sql = "SELECT aa.ACTIVITYSCOPE_VALUE from activity_scope aa LEFT JOIN activity_rule ar ON aa.ACTIVITYRULE_ID = ar.ACTIVITYRULE_ID LEFT JOIN"
- +" activity ac on ar.ACTIVITY_ID = ac.ACTIVITY_ID where ac.ACTIVITY_ID ="+activityId+" and ac.status=3";
- System.out.println(sql);
- Query query = entityManager.createNativeQuery(sql);
- List<Integer> commoditiyIds = (List<Integer>)(query.getResultList());
- List<Commodity> commodities = new ArrayList<Commodity>();
- for(int i=0;i<commoditiyIds.size();i++) {
- String sql2 = "from Commodity c where c.commodityId=:c1";
- Query query2 = entityManager.createQuery(sql2);
- query2.setParameter("c1", commoditiyIds.get(i));
- Commodity c = (Commodity) query2.getResultList().get(0);
- commodities.add(c);
- }
- return commodities;
- }