Search code examples
jsonhibernatejpaspring-roospring-data-jpa

Issue with a @ManyToMany relationship persisting into reference tables


I have a Curriculum entity which is as follows:

@Entity
public class Curriculum {

    @ManyToMany
    private Set<Language> languages;
    ...

I am trying to persist a Curriculum instance but the constraint is that the Language instances are already in database.

How can I make sure that when a call to persist is made, a line is inserted into the curriculum table, the curriculum_languages mapping table but not into the language table as it is a reference table which is already populated?

edit 1:

-Here is the error I get if I don't specify the Cascade.ALL attribute:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.bignibou.domain.Language

-If I do specify the Cascade.ALL, new lines with new IDs are insterted into the language table which is obviously not what I want...

edit 2: Note that I use Spring Data JPA in order to persist my instances and the data coming from the browser is a JSON object as follows:

{"curriculum":{"languages":[{"id":46,"description":"Français"},{"id":30,"description":"Chinois"}],"firstName":"Julianito","dateOfBirth":"1975-01-06","telephoneNumber":"0608965874","workExperienceInYears":3,"maxNumberChildren":1,"drivingLicense":true}}

Solution

  • I forgot to mention that I use optimistic locking. Including the version field in JSon sorted the issue:

    "languages":[{"id":46,"description":"Français","version":0}],...
    

    It would be great if anyone would kindly provide an explanation to this though...

    edit: version field:

    @Version
    @Column(name = "version")
    private Integer Curriculum.version;