HQL

转载 2018年04月17日 10:00:58

查找实体:

        String hql=”from User user ”;
        List<User> list=session.CreateQuery(hql).list();
    where连接:
            from User user where user.age=20;
        from User user where user.age between 20 and 30;
        from User user where user.age in(20,30);
        from User user where user.name is null;
        from User user where user.name like ‘%zx%’;
        from User user where (user.age%2)=1;
        from User user where user.age=20 and user.name like ‘%zx%’;

实体的更新:

        Transaction trans=session.beginTransaction();
        String hql=”update User user set user.age=20 where user.age=18”;
        Query queryupdate=session.createQuery(hql);
        int ret=queryupdate.executeUpdate();
        trans.commit();

实体的删除:

        Transaction trans=session.beginTransaction();
        String hql=”delete from User user where user.age=18”;
        Query queryupdate=session.createQuery(hql);
        int ret=queryupdate.executeUpdate();
        trans.commit();

属性查询:

        List list=session.createQuery(“select user.name from User user ”).list();
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }

        List list=session.createQuery(“select new User(user.name,user.age) from User user ”).list();
        for(int i=0;i<list.size();i++){
        User user=(User)list.get(i);
            System.out.println(user.getName());
            System.out.println(user.getAge());
        }

分组与排序:

       String hql=”select count(user),user.age from User user group by user.age having count(user)>10 ”;
       List list=session.createQuery(hql).list();

参数绑定:

    参数名的绑定:在HQL语句中定义命名参数要用”:”开头

    Query query=session.createQuery(“from User user where user.name=:customername and user.customerage=:age ”);
    query.setString(“customername”,name);
    query.setInteger(“customerage”,age);
    参数位置的绑定: 在HQL查询语句中用”?”来定义参数位置

    Query query=session.createQuery(“from User user where user.name=? and user.age =? ”);
    query.setString(0,name);
    query.setInteger(1,age);

收藏助手
不良信息举报
您举报文章:HQL
举报原因:
原因补充:

(最多只允许输入30个字)