gpt4 book ai didi

java - JPA:何时选择多值关联与元素集合映射

转载 作者:IT老高 更新时间:2023-10-28 20:54:07 24 4
gpt4 key购买 nike

我想更好地了解它们之间的区别

(1) 传统的多值关系/关联

   @Entity -> @OneToMany -> @Entity

(2) JPA2 可嵌入(和基本)类型的集合

  @Entity -> @ElementCollection -> @Embeddable

我看到了语法差异,但想知道是否还有性能影响。在后台,数据库实现看起来非常相似。

直观地说,我通常会将 @ElementCollection 用于组合场景。但即使这样感觉也很像 CascadeType=DELETE

我错过了这里的本质吗?对于某些目的,一种比另一种更有效吗?

谢谢你,J。

最佳答案

Intuitively, I would typically use the @ElementCollection for composition scenarios. But even that feels very similar like CascadeType=DELETE

它们很相似,但有一些细微的差别。 ElementCollection来自 Java Persistence 的页面wikibook 总结得很好:

Emdedded Collections

An ElementCollection mapping can be used to define a collection of Embeddable objects. This is not a typical usage of Embeddable objects as the objects are not embedded in the source object's table, but stored in a separate collection table. This is similar to a OneToMany, except the target object is an Embeddable instead of an Entity. This allows collections of simple objects to be easily defined, without requiring the simple objects to define an Id or ManyToOne inverse mapping. ElementCollection can also override the mappings, or table for their collection, so you can have multiple entities reference the same Embeddable class, but have each store their dependent objects in a separate table.

The limitations of using an ElementCollection instead of a OneToMany is that the target objects cannot be queried, persisted, merged independently of their parent object. They are strictly privately-owned (dependent) objects, the same as an Embedded mapping. Their is no cascade option on an ElementCollection, the target objects are always persisted, merged, removed with their parent. ElementCollection still can use a fetch type and defaults to LAZY the same as other collection mappings.

另见

关于java - JPA:何时选择多值关联与元素集合映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3418683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com