1、普通查询
@Test public void testFindAll(){ String sql = "select * from t_user;"; List<Object[]> user = session.createSQLQuery(sql).list(); for(Object[] objs : user){ System.out.println(objs[0]+"\t"+objs[1]+"\t"+objs[2]); } }
2、转换实体(如果输出指定个别字段,转换实体失败)
@Test public void testFindAll2(){ String sql = "select * from t_user;"; List<User> users = session.createSQLQuery(sql) .addEntity(User.class) .list(); for(User u : users){ System.out.println(u.getName()+"\t"+u.getAge()+"\t"+u.getId()); } }
3、聚合函数
@Test public void testFindCount(){ String sql = "select count(1) from t_user;"; BigInteger count = (BigInteger) session.createSQLQuery(sql).uniqueResult(); System.out.println(count); }
4、命名查询
<sql-query name="findUser"> select * from t_user; </sql-query>
@Test public void testFindUser(){ List<Object[]> user = session.getNamedQuery("findUser") .list(); for(Object[] objs : user){ System.out.println(objs[0]+"\t"+objs[1]+"\t"+objs[2]); } }