Hibernate注解多对多关系理解

发布于 2024-12-10 10:34:00 字数 355 浏览 2 评论 0原文

我已经尝试了两种不同的休眠多对多关系的方法,但我真的找不到它们之间的确切区别。

第一种情况:

@Entity
public class Entity1 implements Serializable {
@ManyToMany
List<Entity2> entitiy2;

第二种情况:

@Entity
public class Entity1 implements Serializable {
@ManyToMany
List<Entity2> entitiy2 = new ArrayList<Entity2>();

I have tried 2 different things with hibernate many to many relationship, but i really couldn't find the exact difference between them.

First Scenario :

@Entity
public class Entity1 implements Serializable {
@ManyToMany
List<Entity2> entitiy2;

Second Scenario :

@Entity
public class Entity1 implements Serializable {
@ManyToMany
List<Entity2> entitiy2 = new ArrayList<Entity2>();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半岛未凉 2024-12-17 10:34:00

对于 Hibernate 来说,没有区别。每次 Hibernate 加载 Entity1 时,其 Entity2 实例列表都将使用自定义非空 Hibernate 列表进行初始化(或在第二种情况下重新初始化)。

对于您自己的代码来说,它确实有所不同。对于第一种情况,每次创建 Entity1 实例时,它都会处于错误状态,Entity2 实例列表为 null 而不是空。每次您想要将新元素添加到列表中并迭代列表时(即使在单元测试中),您都必须先检查列表是否为空。第二种情况更好,因为它以良好的状态初始化对象,其中列表已准备好使用。

For Hibernate, there is no difference. Each time an Entity1 is loaded by Hibernate, its list of Entity2 instances will be initialized (or re-initialized in the second case) with a custom non-null Hibernate list.

For your own code, it does make a difference. With the first case, each time you create an Entity1 instance, it will be in a bad state, with a list of Entity2 instances that is null instead of being empty. Each time you'll want to add a new element to the list of iterate through the list (even in unit tests), you'll have to check before if the list is null or not. The second case is better, since it initializes the object in a good state, where the list is ready to be used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文