使用实体ElementCollection键的JPA级联持久性 [英] JPA cascade persistence with entity ElementCollection keys
问题描述
我有两个这样的JPA实体:
I have two JPA entities like this:
@Entity
class Foo {
@Id
private long id;
// ...
}
@Entity
class Bar {
@ElementCollection(targetClass = String.class, fetch = FetchType.LAZY)
@MapKeyJoinColumn(name = "foo_id", referencedColumnName = "id")
@MapKeyClass(Foo.class)
@Column(name = "content")
@CollectionTable(name = "bar_foo_content",
joinColumns = @JoinColumn(name = "bar_id", referencedColumnName = "id"))
@ManyToMany(cascade = CascadeType.ALL)
private Map<Foo, String> fooContent = Maps.newHashMap();
// ...
}
如您所见,fooContent
字段在Bar
和Foo
之间形成了多对多关系,因此我认为使用@ManyToMany
为该字段指定级联是合适的.但是,当尝试在映射中使用两个Foo → String
值持久保存Bar
时,出现以下异常:
As you can see, the fooContent
field forms a many-to-many relation between Bar
and Foo
, so I thought it would be appropriate to use @ManyToMany
to specify cascading for the field. However, when trying to persist a Bar
with a couple of Foo → String
values in the map, I get the following exception:
javax.persistence.RollbackException: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: <<instance of Foo>>
很显然,EclipseLink不会级联我的Foo
实例的持久性.我应该如何注释fooContent
以获得级联持续工作?
Clearly, EclipseLink does not cascade the persistence of my Foo
instances. How should I annotate fooContent
to get cascaded persists working?
推荐答案
您在这里不需要@ManyToMany
批注. ElementCollection
上的操作始终是级联的.
You don't need @ManyToMany
annotation here. Operations on ElementCollection
s are always cascaded.
这篇关于使用实体ElementCollection键的JPA级联持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!