Hibernate(5)原生sql查询(复杂查询)

 

适用于复杂的多表查询

查询所有对象,返回数组

    @Test
    public void test(){
        //1.获得session
        Session session = HibernateUtils.getCurrentSession();
        //2.获得事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        //3.1书写sql语句
        String sql = "select * from cst_customer";
        //3.2创建sql查询对象
        NativeQuery sqlQuery = session.createSQLQuery(sql);
        //3.3  调用方法查询结果
        List<Object[]> list = sqlQuery.list();
        //sqlQuery.uniqueResult();
        for (Object[] objs: list){
            System.out.println(Arrays.toString(objs));

        }
        //4.提交事务
        tx.commit();


    }

查询所有对象,返回对象

    @Test
    public void test2(){
        //1.获得session
        Session session = HibernateUtils.getCurrentSession();
        //2.获得事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        //3.1书写sql语句
        String sql = "select * from cst_customer";
        //3.2创建sql查询对象
        NativeQuery sqlQuery = session.createSQLQuery(sql);
        //将结果集封装到对象中
        sqlQuery.addEntity(Customer.class);

        //3.3  调用方法查询结果
        List<Customer> list = sqlQuery.list();
        //sqlQuery.uniqueResult();
        System.out.println(list);
        //4.提交事务
        tx.commit();


    }

条件查询

@Test
    public void test3(){
        //1.获得session
        Session session = HibernateUtils.getCurrentSession();
        //2.获得事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        //3.1书写sql语句
        String sql = "select * from cst_customer where cust_id = ?";
        //3.2创建sql查询对象
        NativeQuery sqlQuery = session.createSQLQuery(sql);
        sqlQuery.setParameter(1,1);
        //将结果集封装到对象中
        sqlQuery.addEntity(Customer.class);

        //3.3  调用方法查询结果
        List<Customer> list = sqlQuery.list();
        //sqlQuery.uniqueResult();
        System.out.println(list);
        //4.提交事务
        tx.commit();


    }

 

分页查询

@Test
    public void test4(){
        //1.获得session
        Session session = HibernateUtils.getCurrentSession();
        //2.获得事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        //3.1书写sql语句
        String sql = "select * from cst_customer limit ?,?";
        //3.2创建sql查询对象
        NativeQuery sqlQuery = session.createSQLQuery(sql);
        sqlQuery.setParameter(1,0);
        sqlQuery.setParameter(2,4);
        //将结果集封装到对象中
        sqlQuery.addEntity(Customer.class);

        //3.3  调用方法查询结果
        List<Customer> list = sqlQuery.list();
        //sqlQuery.uniqueResult();
        System.out.println(list);
        //4.提交事务
        tx.commit();


    }

 

 

 

 

 

上一篇:SqlSugar学习总结1(基础操作)


下一篇:SpringMVC框架技术总结(二),Java学习路线指南