如何维护与 Spring Data REST 和 JPA 的双向关系? [英] How to maintain bi-directional relationships with Spring Data REST and JPA?

查看:34
本文介绍了如何维护与 Spring Data REST 和 JPA 的双向关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Spring Data REST,如果您有 OneToManyManyToOne 关系,PUT 操作在非拥有"实体上返回 200 但实际上不会持久化加入的资源.

Working with Spring Data REST, if you have a OneToMany or ManyToOne relationship, the PUT operation returns 200 on the "non-owning" entity but does not actually persist the joined resource.

示例实体:

@Entity(name = 'author')
@ToString
class AuthorEntity implements Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id

    String fullName

    @ManyToMany(mappedBy = 'authors')
    Set<BookEntity> books
}


@Entity(name = 'book')
@EqualsAndHashCode
class BookEntity implements Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id

    @Column(nullable = false)
    String title

    @Column(nullable = false)
    String isbn

    @Column(nullable = false)
    String publisher

    @ManyToMany(fetch = FetchType.LAZY, cascade = [CascadeType.ALL])
    Set<AuthorEntity> authors
}

如果你使用 PagingAndSortingRepository 来支持它们,你可以得到一本 Book,点击书中的 authors 链接并使用要关联的作者的 URI.你不能走另一条路.

If you back them with a PagingAndSortingRepository, you can GET a Book, follow the authors link on the book and do a PUT with the URI of a author to associate with. You cannot go the other way.

如果您对作者执行 GET 并对其 books 链接执行 PUT,则响应将返回 200,但这种关系永远不会持久化.

If you do a GET on an Author and do a PUT on its books link, the response returns 200, but the relationship is never persisted.

这是预期的行为吗?

推荐答案

tl;dr

关键不在于 Spring Data REST 中的任何内容 - 因为您可以轻松地让它在您的场景中工作 - 但要确保您的模型使关联的两端保持同步.

tl;dr

The key to that is not so much anything in Spring Data REST - as you can easily get it to work in your scenario - but making sure that your model keeps both ends of the association in sync.

您在此处看到的问题源于 Spring Data REST 基本上修改了您的 AuthorEntitybooks 属性.这本身并没有在 BookEntityauthors 属性中反映此更新.这必须手动解决,这不是 Spring Data REST 构成的约束,而是 JPA 的一般工作方式.您只需手动调用 setter 并尝试保留结果即可重现错误行为.

The problem you see here arises from the fact that Spring Data REST basically modifies the books property of your AuthorEntity. That itself doesn't reflect this update in the authors property of the BookEntity. This has to be worked around manually, which is not a constraint that Spring Data REST makes up but the way that JPA works in general. You will be able to reproduce the erroneous behavior by simply invoking setters manually and trying to persist the result.

如果删除双向关联不是一种选择(请参阅下文,了解我为什么推荐这样做),使这项工作起作用的唯一方法是确保对关联的更改反映在双方上.通常人们通过在添加书籍时手动将作者添加到 BookEntity 来解决这个问题:

If removing the bi-directional association is not an option (see below on why I'd recommend this) the only way to make this work is to make sure changes to the association are reflected on both sides. Usually people take care of this by manually adding the author to the BookEntity when a book is added:

class AuthorEntity {

  void add(BookEntity book) {

    this.books.add(book);

    if (!book.getAuthors().contains(this)) {
       book.add(this);
    }
  }
}

如果您想确保也传播来自另一端的更改,则还必须在 BookEntity 端添加额外的 if 子句.if 基本上是必需的,否则这两个方法会不断调用自己.

The additional if clause would've to be added on the BookEntity side as well if you want to make sure that changes from the other side are propagated, too. The if is basically required as otherwise the two methods would constantly call themselves.

Spring Data REST,默认情况下使用字段访问,因此您实际上没有可以将此逻辑放入的方法.一种选择是切换到属性访问并将逻辑放入设置器中.另一种选择是使用带有 @PreUpdate/@PrePersist 注释的方法,该方法迭代实体并确保修改在双方都得到反映.

Spring Data REST, by default uses field access so that theres actually no method that you can put this logic into. One option would be to switch to property access and put the logic into the setters. Another option is to use a method annotated with @PreUpdate/@PrePersist that iterates over the entities and makes sure the modifications are reflected on both sides.

如您所见,这给域模型增加了相当多的复杂性.正如我昨天在 Twitter 上开玩笑:

As you can see, this adds quite a lot of complexity to the domain model. As I joked on Twitter yesterday:

#1 双向关联规则:不要使用它们... :)

#1 rule of bi-directional associations: don't use them… :)

如果您尽量不使用双向关系,而是退回到存储库以获取构成关联背面的所有实体,通常会简化问题.

It usually simplifies the matter if you try not to use bi-directional relationship whenever possible and rather fall back to a repository to obtain all the entities that make up the backside of the association.

确定要削减哪一侧的一个很好的启发式方法是考虑关联的哪一侧对您正在建模的领域真正是核心和关键的.在你的情况下,我认为作者没有她写的书而存在是完全没问题的.另一方面,一本没有作者的书根本没有多大意义.所以我将 authors 属性保留在 BookEntity 中,但在 BookRepository 中引入以下方法:

A good heuristics to determine which side to cut is to think about which side of the association is really core and crucial to the domain you're modeling. In your case I'd argue that it's perfectly fine for an author to exist with no books written by her. On the flip side, a book without an author doesn't make too much sense at all. So I'd keep the authors property in BookEntity but introduce the following method on the BookRepository:

interface BookRepository extends Repository<Book, Long> {

  List<Book> findByAuthor(Author author);
}

是的,这需要所有以前可以调用 author.getBooks() 的客户端现在使用存储库.但从积极的方面来说,您已经从域对象中删除了所有杂物,并在此过程中创建了从书籍到作者的清晰依赖方向.书籍取决于作者,但不取决于作者.

Yes, that requires all clients that previously could just have invoked author.getBooks() to now work with a repository. But on the positive side you've removed all the cruft from your domain objects and created a clear dependency direction from book to author along the way. Books depend on authors but not the other way round.

这篇关于如何维护与 Spring Data REST 和 JPA 的双向关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆