我不更新 JPA 关系的双方,但它有效。好的?
这些是我的实体
@Entity
public class User {
@ManyToMany(mappedBy="admins")
private Set<Game> adminForGames = new HashSet<Game>();
@Entity
public class Game {
@ManyToMany
@JoinTable(
name="Game_adminUsers",
joinColumns=@JoinColumn(name="Game_id"),
inverseJoinColumns=@JoinColumn(name="User_id")
)
private Set<User> adminUsers = new HashSet<User>();
,这就是我创建新 Game
的方式:
Game game = new Game(index, name);
game.getAdminUsers().add(someUser);
em.persist(game);
如您所见,我不会更新 someUser
来将新游戏添加到他的 adminForGames 中
,尽管根据 JPA 规范,这是我的责任。
尽管如此,它仍然可以正常工作,这是合乎逻辑的,因为实际上不需要写入 User
记录(因为关系使用连接表)。
它是“偶然”工作的(我的实现是 Hibernate)还是我实际上这样做是正确的?
These are my entities
@Entity
public class User {
@ManyToMany(mappedBy="admins")
private Set<Game> adminForGames = new HashSet<Game>();
@Entity
public class Game {
@ManyToMany
@JoinTable(
name="Game_adminUsers",
joinColumns=@JoinColumn(name="Game_id"),
inverseJoinColumns=@JoinColumn(name="User_id")
)
private Set<User> adminUsers = new HashSet<User>();
And this is how I create a new Game
:
Game game = new Game(index, name);
game.getAdminUsers().add(someUser);
em.persist(game);
As you can see I don't update the someUser
to add the new game to his adminForGames
, though according though the JPA spec this is my responsibility.
Still, it works fine, which is logical because the User
record doesn't actually need to be written to (because the relationship uses a join table).
Does it work "by chance" (my implementation is Hibernate) or am I actually doing this correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是“机会”。这就是 JPA 预期的工作方式。
This isn't "chance." This is how JPA is expected to work.
我对 JPA 规范的理解是,用户有责任在内存中设置正确的关系。
对于数据库,设置关系的拥有方就足够了(这就是您所做的)。因此(从理论上讲)如果您仅设置非拥有方,则它不应该起作用。
My understanding from the JPA spec is that it is the user's responsibility to set correct relations in memory.
For the database it is sufficient to set the owning side of the relationship (and that is what you did). So (from theory) it should not work if you set the non-owning side only.