数据库
首页 > 数据库> > Hibernate(5)原生sql查询(复杂查询)

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();


    }

 

 

 

 

 

标签:Hibernate,tx,list,查询,sqlQuery,session,sql
来源: https://blog.csdn.net/qq_38125626/article/details/97646751