Hibernate中三种常用的数据库查询

HQL查询:

public List getUserByNameAndAge(String name, Integer age) {
	Session session = getSession();
	//from后面是对象,不是表名
	String FIND_USER_BY_ID = "from User where name=:name and age=:age";
	Query query = session.createQuery(FIND_USER_BY_ID).setString(
			"name", name).setInteger("age", age);
	return query.list();
}
对象化查询Criteria方法:

public User getUserById(Long id) {
	Criteria criteria = getSession().createCriteria(User.class);
	criteria.add(Restrictions.eq("id", id));
	return (User)criteria.uniqueResult();
}

SQL查询:

public User getUserById(Long id) {
		
	String sql = "select Id, Name, Age from User where Id=:Id";
	SQLQuery query = getSession().createSQLQuery(sql);
	
	//设置参数
	query.setParameter("Id", id);
	
	//设置查询列的类型
	query.addScalar("Id", new org.hibernate.type.LongType());
	query.addScalar("Name", new org.hibernate.type.StringType());
	query.addScalar("Age", new org.hibernate.type.IntegerType());
	
	//设置查询结果的对象类型
	query.setResultTransformer(Transformers.aliasToBean(User.class));
	
	return (User)query.uniqueResult();
}



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