hibernate使用手写sql以及对结果list的处理
Session sees=simpleDAO.getSessionFactory().openSession(); String sql = "select * from fhcb_08_tbl_user_right"; SQLQuery query = sees.createSQLQuery(sql); List<?> list = query.list(); for(Object o: list){ Object[]objects=(Object[])o; System.out.println((BigDecimal) objects[0]+ "::" + (String) objects[2]); }
其实hibernate查询出来的结果集不能直接用,得到的是一个Object数组,里面每个obj其实都是一个实体类,遍历拿到obj还不能直接当做实体对象操作,这个obj也是一个数组,元素顺序就是数据库字段顺序,取到obj里面的元素需要类型强转才能使用,正常操作。
如果类型拿不准,直接可以用objects[0].toString()方法取出里面的值。
对count的获取方法 String sql = "SELECT COUNT(*) FROM fhcb_08_tbl_login_record WHERE USERNAME="+"'"+userName+"'"; Session sees=simpleDAO.getSessionFactory().openSession(); Query query = sees.createSQLQuery(sql).addScalar("COUNT(*)", StandardBasicTypes.INTEGER); int count=(Integer)query.uniqueResult();
1sess.createSQLQuery("SELECT NAME, BIRTHDATE FROM CATS") 2 .setResultTransformer(Transformers.aliasToBean(CatDTO.class)) 1String sql = "SELECT ID as {c.id}, NAME as {c.name}, " + 2 "BIRTHDATE as {c.birthDate}, MOTHER_ID as {c.mother}, {mother.*} " + 3 "FROM CAT_LOG c, CAT_LOG m WHERE {c.mother} = c.ID"; 4 5List loggedCats = sess.createSQLQuery(sql) 6 .addEntity("cat", Cat.class) 7 .addEntity("mother", Cat.class).list();