hibernate select 查询方式总结


1. 查询整个映射对象所有字段(查询整个映射对象所有字段,填充到List<User>中)

List<User> result = hibernateTemplate.executeFind(new HibernateCallback(){
	public Object doInHibernate(Session session)
		throws HibernateException, SQLException {
	Query query = session.createQuery("from User as u");
	List<User> result = query.list();
	return result;
	}
});
return result;

2查询单个字段,(查询整个映射对象单一字段,填充到List<String>中)

List<User> result = hibernateTemplate.executeFind(new HibernateCallback(){
	public Object doInHibernate(Session session)
		throws HibernateException, SQLException {
	Query query = session.createQuery("select name from User as u");
	List<String> result = query.list();
	return result;
	}
});
return result;


3查询多个字段,(查询整个映射对象多个字段,返回Object[],可以new两个ArrayList,不常使用)

List result = hibernateTemplate.executeFind(new HibernateCallback(){
	public Object doInHibernate(Session session)
		throws HibernateException, SQLException {
	Query query = session.createQuery("select name,pass,registeredTime from User as u");
	List result = query.list();
	return result;
	}
});
return result;

遍历这个Object数组

List name = new ArrayList();
for (int i = 0; i < result.size(); i++) {
	Object[] objArray = (Object[])result.get(i);
	for(Object obj : objArray){
		name.add(obj);
	}
}

4查询多个字段,(查询整个映射对象多个字段,通过select new com.bict.entity.User(),必须加包名,返回自定义的类User,可以填充到模板,常使用)

List<User> result = hibernateTemplate.executeFind(new HibernateCallback(){
	public Object doInHibernate(Session session)
		throws HibernateException, SQLException {
			Query query = session.createQuery("select new com.bict.entity.User(u.id,u.name,u.pass,u.registeredTime) from User as u");
			query.setFirstResult((pageNum - 1) * Pagination.PAGESIZE);
			query.setMaxResults(Pagination.PAGESIZE);
			List<User> result = query.list();
			return result;
		}
	});
	return result;
}

实体类有带参数的构造方法,并且参数与查询的字段对应,Date类型引用java.util.Date










你可能感兴趣的:(Hibernate,HQL)