为什么我需要在JPA中同时设置实体 [英] Why do I need to set the entities both ways in JPA

查看:64
本文介绍了为什么我需要在JPA中同时设置实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个实体:

@Entity
public class Pilot implements Serializable {
....
    @ManyToOne
    @JoinColumn(name = "FLIGHT_ID")
    private Flight flight;
}

@Entity
public class Flight implements Serializable {
....
    @OneToMany(mappedBy = "flight")
    private List<Pilot> pilots;
}

我正在使用EJB向航班添加飞行员:

I am using an EJB to add a pilot to a flight:

public void addPilotToFlight(String pilotId, String flightId) {
    <code to find Flight f>
    <code to find Pilot p>
    p.setFlight(f);
    f.getPilots().add(p); // Why do I need this one?
}

我的困惑是为什么我需要双向链接对象?

My confusion is why do I need to link objects both ways?

我尝试了带和不带 f.getPilots().add(p); 部分的代码,在DB中看起来完全一样.但是,当我尝试对同一飞行实体对象使用 f.getPilots(); 时,只有在完成上述双向链接后,它才会显示.任何人都可以对此有所了解吗?我将不胜感激.预先感谢.

I have tried the code with and without the f.getPilots().add(p); part, in DB it looks the exact same. However, when I try to use f.getPilots(); for the same flight entity object, it shows only if I had done the above both-way linking. Could anyone please shed some light on this? I'd be very grateful. Thanks in advance.

推荐答案

您的问题似乎旨在询问为什么您必须保持双向关系的双方,这是一个常见的问题,也是造成混乱的根源.

Your question seems aimed at asking why you have to maintain both sides of a bidirectional relationship, which is a common question and source of confusion.

CMP 2.0试图在后台执行关系维护和魔术,但是开销和缺乏控制是一个问题(IMO),并且未包含在 JPA 中.相反,JPA实体是普通的旧Java对象.这意味着,如果您希望对关系的一侧所做的更改能够反映到另一侧,则必须自己进行更改.

CMP 2.0 tried to perform relationship maintenance and magic behind the scenes, but the overhead and lack of control was a problem (IMO) and it was not included in JPA. Instead, JPA entities are meant to be plain old java objects. That means if you want changes made to one side of a relationship to be reflected in the other, you must make them yourself.

混淆之处在于,如果您修改关系的一侧而不是另一侧,则有时数据库将正确更新,有时不正确,并且有时双方都将显示更改.这完全取决于更改的方向,以及如何从数据库中缓存和刷新实体.对拥有方的更改将保存到数据库中,并且JPA允许进行缓存,因此,非拥有方的更改直到从数据库中刷新后才可能反映这些更改.

The confusion will be that if you modify one side of a relationship and not the other, sometimes the database will get updated correctly, sometimes not, and sometimes both sides will show the change. It all depends on which side you change, and how the entities are cached and refreshed from the database. Changes to the owning side are persisted to the database, and JPA allows for caching, so the non-owning side may not reflect these changes until it is refreshed from the database.

最佳实践是,如果您希望对象模型与数据库保持同步,则对应用程序一侧所做的任何更改都应由应用程序进行.

The best practices is that any change you make to one side should be made to the other by the application if you want your object model to remain in sync with the database.

这篇关于为什么我需要在JPA中同时设置实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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