Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA cascade persistence with entity ElementCollection keys

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();
    // ...
}

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>>

Clearly, EclipseLink does not cascade the persistence of my Foo instances. How should I annotate fooContent to get cascaded persists working?

like image 839
dflemstr Avatar asked Oct 17 '13 13:10

dflemstr


1 Answers

You don't need @ManyToMany annotation here. Operations on ElementCollections are always cascaded.

like image 139
Uooo Avatar answered Sep 28 '22 08:09

Uooo