Multiple product can be saved under multiple categories. Like: Mango can be used as Frui
At last, I got my solution for Many-to-Many connection in JPA.
In a JPA many-to-many relationship, if cascade type has been set at CascadeType.PERSIST
(or CascadeType.ALL
, which includes CascadeType.PERSIST), then while saving the parent and updating it with references of the child, it will try to save the child again.
Following Issues can appear:
Child is already in persistence store (A detached instance has been passed)
-in this case it will throw an exception “org.hibernate.PersistentObjectException: detached entity passed to persist”
Use this:
@ManyToMany(fetch = FetchType.EAGER,
cascade = {
CascadeType.MERGE,
CascadeType.REFRESH
})
@JoinTable(name = "commodity_genre", joinColumns = {
@JoinColumn(name = "commodity_id", referencedColumnName = "id") }, inverseJoinColumns = {
@JoinColumn(name = "genre_id", referencedColumnName = "id") })
@JsonManagedReference
private List<Genre> genres;
Instead of:
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.MERGE,
CascadeType.PERSIST
})
@JoinTable(name = "commodity_genre", joinColumns = {
@JoinColumn(name = "commodity_id", referencedColumnName = "id") }, inverseJoinColumns = {
@JoinColumn(name = "genre_id", referencedColumnName = "id") })
@JsonManagedReference
private List<Genre> genres;
For JPA, the best option would be to query for entity on the server side before trying to save it.
CascadeType.PERSIST
will take care of it.CascadeType.PERSIST
should be removed and
cascade={CascadeType.MERGE,CascadeType.REFRESH}
should be usedPersisting a detached entity in JPA
For me the issue was using Cascade.ALL
instead of Cascade.MERGE
.