我正在Spring Data JPA Specification
中加入三个表,如下所示:
public static Specification<Contact> findByStructureCode(final String code) {
return new Specification<Contact>() {
@Override
public Predicate toPredicate(Root<Contact> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(root.join(Contact_.contactToStructures)
.join(ContactToStructure_.structureCodes)
.get(StructureCode_.code), code);
}
};
}
但是,这给了我很好的
NullPointerException
。java.lang.NullPointerException: null
at org.hibernate.jpa.criteria.path.AbstractFromImpl.constructJoin(AbstractFromImpl.java:345) ~[hibernate-entitymanager-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.jpa.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:333) ~[hibernate-entitymanager-4.3.8.Final.jar:4.3.8.Final]
at org.hibernate.jpa.criteria.path.AbstractFromImpl.join(AbstractFromImpl.java:324) ~[hibernate-entitymanager-4.3.8.Final.jar:4.3.8.Final]
at my.package.ContactSpecification$3.toPredicate(ContactSpecification.java:83) ~[MyProject-1.0.0.jar:na]
请注意,我已经用伪造信息替换了最后一行中的package和jar信息。我的代码中堆栈跟踪引用的行是
.join(ContactToStructure_.structureCodes)
。我认为这是由于并非所有
Contact
行在我的数据库中都有对应的ContactToStructure
行而引起的。因此,如何进行第一次联接以允许具有空
Contact
集的contactToStructures
实体,并仅返回具有非空contactToStructures
集的联系人?这是实体及其元模型的相关部分。
Contact.java
@Entity
@Table(name = "CONTACT", schema = "myschema")
public class Contact {
@OneToMany(mappedBy = "contact", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<ContactToStructure> contactToStructures = new HashSet<>(0);
}
Contact_.java
@StaticMetamodel(Contact.class)
public class Contact_ {
public static volatile SetAttribute<Contact, ContactToStructure> contactToStructures;
}
ContactToStructure.java
@Entity
@Table(name = "CONTACT_TO_STRUCTURE", schema = "myschema")
public class ContactToStructure {
@OneToMany(fetch=FetchType.LAZY, cascade = {CascadeType.ALL}, mappedBy="contactToStructure")
private Collection<StructureCode> structureCodes = new ArrayList<>();
}
ContactToStructure_.java
@StaticMetamodel(ContactToStructure.class)
public class ContactToStructure_ {
public static volatile SetAttribute<ContactToStructure, StructureCode> structureCodes;
}
StructureCode.java
@Entity
@Table(name = "STRUCTURE_CODE", schema = "myschema")
public class StructureCode {
@Column(name = "CODE")
private String code;
}
StructureCode_.java
@StaticMetamodel(StructureCode.class)
public class StructureCode_ {
public static volatile SingularAttribute<StructureCode, String> code;
}
最佳答案
如果仍然相关
尝试进行以下更改ContactToStructure_.java
:
public static volatile SetAttribute<Version, UseCase> useCases;
至:
public static volatile CollectionAttribute<Version, UseCase> useCases;