使用实体ElementCollection键的JPA级联持久性 [英] JPA cascade persistence with entity ElementCollection keys

查看:192
本文介绍了使用实体ElementCollection键的JPA级联持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的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字段在BarFoo之间形成了多对多关系,因此我认为使用@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 ElementCollections are always cascaded.

这篇关于使用实体ElementCollection键的JPA级联持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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