javax.persistence 一对多 - 它是如何工作的?
假设我有两个实体:用户和消息。用户有一个名为“messages”的字段,其中包含消息列表并用“@manyToOne”进行注释,消息有一个名为“owner”的字段,如下所示:
用户:
@实体
类用户{
...
@OneToMany(mappedBy = "所有者", 级联 = CascadeType.ALL)
私人列表消息;
...}
信息:
@实体
班级留言{
...
@ManyToOne(fetch = FetchType.LAZY)
私人用户所有者;
...
}
- 当添加新消息并将所有者设置为某个用户时,持久性是否知道将另一个元素添加到用户对象的“消息”列表中?
换句话说:当创建消息并设置“所有者”时 - 相应的用户“消息”列表是否自动增加一?
- 我很高兴看到一些代码示例。网络上充满了难以理解的复杂示例......
Say that I have 2 Entites of User and Message. User has a field called "messages" that has a list of messages and is annotated with "@manyToOne" and Message has a field called "owner" like the following:
User:
@Entity
Class User{
...
@OneToMany(mappedBy = "owner", cascade
= CascadeType.ALL)
private List messages;
...}
Message:
@Entity
Class Message{
...
@ManyToOne(fetch = FetchType.LAZY)
private User owner;
...
}
My question - when adding a new message and setting the owner to be certain user, does the persistence knows to add another element to the User Object's "messages" list?
In other words: when creating a message and setting the "owner" - does the appropriate User "messages" list automatically increased by one?
- I'll be glad to see some code example. The web is full of complex examples that are hard to understand...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,要编写严格正确的代码,您需要在内存中维护双方或双向关系。它不会因为设置属性而自动将元素添加到其他位置的集合中。
如果您从数据库刷新您的用户或以其他方式重新加载它,新消息将会出现,但在具有 L2 缓存的系统中这仍然不完全安全。您应该始终保持双方的关系,以实现最大程度的可移植性。
在您的 User 实体上,类似这样的情况并不少见:
No, to write strictly correct code you need to maintain both sides or your bidirectional relationships in memory. It's not going to automagically add an element to a collection somewhere else as a result of setting a property.
The new message will be there if you refresh your User from the database or otherwise reload it, but that still isn't entirely safe in systems with L2 caching. You should always maintain both sides of the relationship for maximum portability.
Something like this is not that uncommon to see on your User entity: