在Spring Data中加入2个文档的最佳方法是什么?

时间:2018-06-10 18:16:20

标签: java mongodb spring-data spring-mongo

我有2个课程AuthorBook

@NoArgsConstructor
@AllArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
class Person {

    @Id
    private BigInteger id;

    private String firstName;

    private String surName;

    @JsonFormat(pattern="yyyy-MM-dd")
    private LocalDate dateOfBirth;

    private boolean deleted;

}


@NoArgsConstructor
@Getter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public final class Author extends Person {

    @Builder
    public Author(BigInteger id, String firstName, String surName, LocalDate dateOfBirth, String bio, boolean deleted) {
        super(id, firstName, surName, dateOfBirth, deleted);
        this.bio = bio;
    }

    private String bio;

}


@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
@EqualsAndHashCode
@ToString
public final class Book {

    @Id
    private BigInteger id;

    private String title;

    @DBRef
    private Author author;

}

我应该如何处理未被删除作者的书籍? 如果我这样做:

@Repository
public interface BookRepository extends MongoRepository<Book, BigInteger> {

    Set<Book> getByAuthor_Deleted(boolean isDeleted);

}

然后抛出org.springframework.data.mapping.MappingException: Invalid path reference author.deleted! Associations can only be pointed to directly or via their id property!异常。

你能澄清一下我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

试试这个。这应该有用。

Book findByAuthor_IdAndAuthor_Deleted(Biginteger id, boolean isDeleted)

将id和false传递给此函数。