我有使用Spring数据JPA规范从实体Person获取列表的问题(由于分页)。我需要按人获取所有注释,但是这两个实体之间的依赖关系在“人”方面。我不知道如何创建我的谓词,因为Note不包含与Person相关的任何属性。

我只是可以用Persons getter来获取List,但是我不能使用这种方式,因为我需要对返回的数据进行分页。

@Entity
public class Person implements Serializable {

    @Id
    private Long personId;

    @OneToMany
    @JoinColumn(name = "personId")
    private List<Note> notes;

}

@Entity
public class Note implements Serializable {

    @Id
    private Long noteId;
}

通常,我会写类似这样的东西,但我在Note中没有属性人员,并且在此阶段无法重新映射数据库。
public static Specification<Note> notesByPerson(final Long personId) {
        return new Specification<Note>() {
            @Override
            public Predicate toPredicate(final Root<Note> root, final CriteriaQuery<?> query,
                    final CriteriaBuilder builder) {

                final Path<Person> per = root.<Person> get("person");

                return builder.equal(per.<Long> get("personId"), personId);

            }
        };
    }

谢谢,
Zdend

最佳答案

解决了..

public static Specification<Note> notesByPerson(final Long personId) {
        return new Specification<Note>() {

            @Override
            public Predicate toPredicate(final Root<Note> noteRoot, final CriteriaQuery<?> query,
                    final CriteriaBuilder cb) {

                final Subquery<Long> personQuery = query.subquery(Long.class);
                final Root<Person> person = personQuery.from(Person.class);
                final Join<Person, Note> notes = person.join("notes");
                personQuery.select(notes.<Long> get("noteId"));
                personQuery.where(cb.equal(person.<Long> get("personId"), personId));

                return cb.in(noteRoot.get("noteId")).value(personQuery);
            }
        };
    }

09-11 19:50
查看更多