【问题标题】:Spring Data REST throwing error when using JPA CriteriaQuery with joins将 JPA CriteriaQuery 与连接一起使用时 Spring Data REST 抛出错误
【发布时间】:2015-04-10 01:31:36
【问题描述】:

将 Spring Data REST 与 JPA/Hibernate 一起使用并通过 REST 公开 spring JpaRepository 时,我收到 JPA Criteria 查询错误。这是一个 Spring Boot 应用程序。

几个相关实体:

@Entity
public class Appointment {  
...  
...  
@ManyToOne(fetch=FetchType.EAGER)  
@JoinColumn(name="doctor_id", insertable=false, updatable=false)  
private Doctor doctor;  
...  
...  
}  

@Entity
public class Doctor {  
...  
...  
@Column(name = "doctor_name")  
private String doctorName = "";  
...  
...  
}  

试图返回与医生姓名匹配的约会列表,我有如下构建的 JPA 规范:

public Specification<Appointment> getSpecification() {
    return new Specification<Appointment>() {

        Join<Appointment, Doctor> doctorJoin;

        @Override
        public Predicate toPredicate(Root<Appointment> root, 
                CriteriaQuery<?> query, 
                CriteriaBuilder cb) {
            Predicate p = cb.conjunction();
            ... //other critieria
            p = addDoctorCriteria(p, cb, root, Doctor_.doctorName, getDoctorName());

            return p;
        }


        private Predicate addDoctorCriteria(Predicate p,
                CriteriaBuilder cb, Root<Appointment> root, SingularAttribute<Doctor, String> property, String value) {

            value = value + '%';

            if (doctorJoin == null) {
                doctorJoin = root.join(Appointment_.doctor);
            }

            p = cb.and(p, cb.like(cb.lower(doctorJoin.<String>get(property)), value));

            return p;
        }
    };
}

这会引发以下异常:

org.hibernate.hql.internal.ast.QuerySyntaxException:  
Invalid path: 'generatedAlias1.doctorName'  
[select count(generatedAlias0) from my.package.Appointment as generatedAlias0   
where ( 1=1 ) and ( lower(generatedAlias1.doctorName) like :param0 )];  

看起来连接查询不正确 - from 子句中没有“generatedAlias1”。当 Spring 尝试获取行数以构建分页信息时,似乎正在发生这种情况。其他依赖于 Appointment 属性的标准(即没有加入)效果很好。

我的 JPA 加入是否正确?有关如何纠正此错误的任何建议?

【问题讨论】:

    标签: spring-data-jpa spring-data-rest


    【解决方案1】:

    如果有人遇到这个问题,我是这样工作的:

    Root<Doctor> doctor = query.from(Doctor.class);
    Predicate j1 = cb.equal(root.get(Appointment_.doctor), doctor);
    Predicate c1 =  cb.like(cb.lower(doctor.<String>get(Doctor_.doctorName)), getDoctorName() + '%');
    p = cb.and(p, cb.and(j1, c1));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 2013-10-04
      • 2014-10-21
      相关资源
      最近更新 更多