在Spring Data JPA规范中允许三个表连接中的空集

时间:2015-11-24 20:04:22

标签: java spring hibernate jpa spring-data-jpa

我正在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]

请注意,我已使用虚假信息替换了最后一行中的包和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;
}

1 个答案:

答案 0 :(得分:0)

如果仍然相关 尝试进行以下更改ContactToStructure_.java

public static volatile SetAttribute<Version, UseCase> useCases;

要:

public static volatile CollectionAttribute<Version, UseCase> useCases;