zoukankan      html  css  js  c++  java
  • Hibernate JPA 动态criteria语句针对null查询条件的特殊处理

    最近原Hibernate项目需要添加一个条件,结构有点类似下面的格式,学生和房间是多对一的关系,现在要查询所有没有房间的学生。

    Class Student{

      @ManyToOne

      Room room;
    }

    一开始的查询语句是这样的:

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
            CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class);
            Root<Student> root = criteriaQuery.from(Order.class);
            criteriaQuery.select(root);
        //多条件查询
            Predicate restrictions = criteriaBuilder.conjunction();
            //组合条件
           restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("room"), null));
            //将条件添加到查询
            criteriaQuery.where(restrictions);
            

    发现项目查询时会报错,最后查询文档http://www.objectdb.com/java/jpa/query/jpql/literal#Criteria_Query_Literals_

    发现在JPA动态查询时,条件全是Expression类型

    所以不能直接使用null,而需要把null转换成Expression类型,语句如下:

    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("room"), criteriaBuilder.nullLiteral(Room.class)));

    修改完查询正常
  • 相关阅读:
    JS 数组总结
    JS 数据类型及其判断
    CSS 优先级
    正则表达式及其使用例子
    常见的图片格式
    React 箭头函数的使用
    手动搭建 react+webpack 开发环境
    JS 函数参数及其传递
    JS 中的 this 指向问题
    JS 中函数的 length 属性
  • 原文地址:https://www.cnblogs.com/chenkeyu/p/9007626.html
Copyright © 2011-2022 走看看