Hibernate SQL查询 也是可以自动装实体的

主要是createSQLQuery后面要跟addEntity……

http://docs.jboss.org/hibernate/core/4.1/javadocs/org/hibernate/SQLQuery.html#addEntity(java.lang.Class)

http://docs.jboss.org/hibernate/core/4.1/manual/en-US/html/ch18.html#d5e8271

比如

	/**
	 * 
	 * findAllGoods:根据分类parent获取所有商品,暂未分页
	 * TODO 分页
	 * 
	 * @author 刘各欢
	 * @param parentId
	 * @return
	 * @since  Ver 1.1
	 */
	@SuppressWarnings("unchecked")
	public List<Goods> findAllGoods(String parentId){
	Session session = getSession();
	String sql = "";
	List<Goods> list = null;
	if(parentId == null ||"".equals(parentId)){
		sql = "SELECT * FROM t_goods WHERE cat IN (SELECT id FROM t_cat WHERE id IN (SELECT id FROM t_cat WHERE parent IS NULL))";	
		Query query = session.createSQLQuery(sql).addEntity(Goods.class);
		list = query.list();
	}else{
		sql = "SELECT * FROM t_goods WHERE cat IN (SELECT id FROM t_cat WHERE id IN (SELECT id FROM t_cat WHERE parent = :parentId))";
		Query query = session.createSQLQuery(sql).addEntity(Goods.class);
		query.setParameter("parentId", parentId);
		list = query.list();
	}
	    return list;
	}

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(Hibernate)