Session session = null;
try {
session = HibernateSessionFactory.getSession();
session.beginTransaction();
//标量查询(Scalar queries)
//它们都将返回一个Object数组(Object[])组成的List,数组每个元素都是user表的一个字段值。
//Hibernate会使用ResultSetMetadata来判定返回的标量值的实际顺序和类型。
//session.createSQLQuery("SELECT * FROM user").list();
//session.createSQLQuery("SELECT id, userName FROM user").list();
//SQLQuery query = session.createSQLQuery("select * from user where id = ?");
//query.setParameter(0, 12);
List results = session.createSQLQuery("SELECT id, userName FROM user").list();
System.out.println(((Object[]) results.get(0))[1]);
//实体查询(Entity queries)
//通过addEntity()让原生查询返回实体对象。
//session.createSQLQuery("SELECT * FROM user").addEntity(User.class);
//session.createSQLQuery("SELECT id, userName FROM user").addEntity(User.class);
//假若实体在映射时有一个many-to-one的关联指向另外一个实体,在查询时必须也返回那个实体,
//否则会导致发生一个"column not found"的数据库错误。
results = session.createSQLQuery("SELECT id, name, sex, clazz_id FROM student")
.addEntity(Student.class).list();
for(Iterator iterator = results.iterator(); iterator.hasNext(); ) {
Student stu = (Student) iterator.next();
System.out.println("clazzName=" + stu.getClazz().getName());
}
//处理关联和集合类
//join查询会在每行返回多个实体对象,处理时需要注意 。
results = session.createSQLQuery("select {user.*}, {dept.*} from user user, department dept where user.dept_id = dept.id")
.addEntity("user", User.class)
.addJoin("dept", "user.department")
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
.list();
Map map = (HashMap) results.get(0);
User user = (User) map.get("user");
System.out.println(user.getUserName());
System.out.println(user.getDepartment().getDeptName());
results = session.createSQLQuery("select {user.*}, {dept.*} from user user, department dept where user.dept_id = dept.id")
.addEntity("user", User.class)
.addJoin("dept", "user.department")
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
Department dept = (Department) results.get(0);
System.out.println(dept.getDeptName());
session.getTransaction().commit();
} catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateSessionFactory.closeSession();
}
* 对原生SQL查询执行的控制是通过SQLQuery接口进行的,通过执行Session.createSQLQuery()获取这个接口。