代码改变世界

15、Hibernate的原生sql查询,优化Hibernate的查询效率

2015-10-11 21:47  怡红院丿无痕  阅读(444)  评论(0编辑  收藏  举报
public class TestSQL {
    
    @Test
    public void test01() {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            List<Student> stus = session.createSQLQuery("select * from t_stu where name like ?")
                    .addEntity(Student.class)
                    .setParameter(0, "%孔%")    
                    .setFirstResult(0).setMaxResults(10)
                    .list();
            for(Student stu:stus) {
                System.out.println(stu.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.close(session);
        }
    }
    
    @Test
    public void test02() {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            List<Object[]> stus = session.createSQLQuery("select {stu.*},{cla.*},{spe.*} from " +
                    "t_stu stu left join t_classroom cla on(stu.cid=cla.id) " +
                    "left join t_special spe on(spe.id=cla.spe_id) where stu.name like ?")
                    .addEntity("stu",Student.class)
                    .addEntity("cla",Classroom.class)
                    .addEntity("spe",Special.class)
                    .setParameter(0, "%孔%")    
                    .setFirstResult(0).setMaxResults(10)
                    .list();
            Student stu = null;
            Classroom cla = null;
            Special spe = null;
            List<StuDto> list = new ArrayList<StuDto>();
            for(Object[] obj:stus) {
                stu = (Student)obj[0];
                cla = (Classroom)obj[1];
                spe = (Special)obj[2];
                list.add(new StuDto(stu, cla, spe));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.close(session);
        }
    }
    
    @Test
    public void test03() {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            List<StudentDto> stus = session.createSQLQuery("select stu.id as sid,stu.name as sname," +
                    "stu.sex as sex,cla.name as cname,spe.name as spename from " +
                    "t_stu stu left join t_classroom cla on(stu.cid=cla.id) " +
                    "left join t_special spe on(spe.id=cla.spe_id) where stu.name like ?")
                    .setResultTransformer(Transformers.aliasToBean(StudentDto.class))
                    .setParameter(0, "%孔%")    
                    .setFirstResult(0).setMaxResults(10)
                    .list();
            for(StudentDto sd:stus) {
                System.out.println(sd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.close(session);
        }
    }
    
    
    
}