4、hibernate查询语言(HQL)

1、HQL(Hibernate Query language)

hibernate查询语言:主要用面向对象的思维来编写SQl语句,形成hibernate查询语句

1.1、查询所有:

From order      //order是对象名不是表名

   //查询所有

    public void findAll(){

        //得到seesion

        Session session = YtUserUtils.openSession();



        String hql = "from UserinfoEntity"; //找对象 不是表

        //createQuery 前面是hql,后面是指向要查询的内容

        Query  query = session.createQuery(hql, UserinfoEntity.class);

        //拿到结果集

        List  resultList = query.getResultList();

        //遍历结果集,输出

        for (UserinfoEntity userinfoEntity:resultList) {

            System.out.println(userinfoEntity.getUid() + "\t" + userinfoEntity.getUserName() + "\t" + userinfoEntity.getUserPass());

        }

       

        //关闭session

        session.close();

    }

别名查询: String hql = “select ue from UserInfoEntity ue”;

1.2、分页查询:

//分页查询

    public void findByPage(int start,int size){

        //得到seesion

        Session session = YtUserUtils.openSession();



        String hql = "from UserinfoEntity"; //找对象 不是表

        //createQuery 前面是hql,后面是指向要查询的内容

        Query  query = session.createQuery(hql, UserinfoEntity.class);

        //设置起始位置

        query.setFirstResult(start);  //从0开始

        //设置每次取多少条记录

        query.setMaxResults(size);

        //拿到结果集

        List  resultList = query.getResultList();

        //遍历结果集,输出

        for (UserinfoEntity userinfoEntity:resultList) {

            System.out.println(userinfoEntity.getUid() + "\t" + userinfoEntity.getUserName() + "\t" + userinfoEntity.getUserPass());

        }



        //关闭session

        session.close();

    }

1.3、条件查询:(索引占位符)

//条件查询(索引占位符)

    public void findByIdHql(Integer uid){

        //得到session

        Session session = YtUserUtils.openSession();



        //hql

        String hql = "from UserinfoEntity where uid = ?";

        Query  query = session.createQuery(hql, UserinfoEntity.class);

        //设置参数值

        query.setParameter(0,uid);

        //获取单个对象

        UserinfoEntity userinfoEntity = query.uniqueResult();

        System.out.println(userinfoEntity.getUid() + "\t" + userinfoEntity.getUserName() + "\t" + userinfoEntity.getUserPass());

        //关闭链接

        session.close();

    }

1.4、条件查询:(命名占位符)

4、hibernate查询语言(HQL)_第1张图片

 //条件查询(命名占位符)

    public void findByIdHqlByName(Integer uid){

        //得到session

        Session session = YtUserUtils.openSession();

        //hql

        String hql = "from UserinfoEntity where uid =:uid";

        Query  query = session.createQuery(hql, UserinfoEntity.class);

        //设置参数值

        query.setParameter("uid",uid);

        //获取单个对象

        UserinfoEntity userinfoEntity = query.uniqueResult();

        System.out.println(userinfoEntity.getUid() + "\t" + userinfoEntity.getUserName() + "\t" + userinfoEntity.getUserPass());

        //关闭链接

        session.close();

    }

 

 

你可能感兴趣的:(hibernate)