0

I have two entity linked with many to many relationship: Movie and Actor

Movie

public class Movie {
    @Id
    private  String imdbId;
    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER, targetEntity = Actor.class)
    private Set<Actor> actor;
}

Actor

public class Actor {
    @Id
    private  String actorId;
}

It is a restful api and I am posting json to MovieController. My json is:

{
  "imdbId": "tt2395424",
  "actor" : [{"actorId" : "0001"}, {"actorId" : "0002"}]
}

This is working perfectly fine and the actor is populated automatically. But when I insert a new movie with same actorId it throws error that actor is already present. I am confused because as far as I know Hibernate compares the id before insertion if not present it will insert else just map it. Can you please tell me where I am going wrong?

Ankan Kumar Giri
  • 243
  • 1
  • 3
  • 12

1 Answers1

1

The issue is with the CascadeType.ALL above actor set in Movie class. What CascadeType.ALL does is perform the same operation on the embedded entities as for parent entity. The save action will try to save the actor in the Actor table, if the actor id is already present in DB then save will throw error. Try to use saveOrUpdate instead of save operation on movie entity.

Ravi Sharma
  • 197
  • 1
  • 4
  • But I am using persist...what is the other alternative to saveOrUpdate when using persist to save? – Ankan Kumar Giri Aug 11 '17 at 04:01
  • You can use merge instead of persist, this is an alternative to saveOrUpdate. Find more details on https://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge – Ravi Sharma Aug 11 '17 at 04:14
  • Thanks..this works, but any idea about auto-generated ID, because for those I am afraid, it creates duplicate – Ankan Kumar Giri Aug 11 '17 at 04:25
  • I had done some checking before insertion, I think that is only the solution because hibernate doesn't check for auto-generated IDs. – Ankan Kumar Giri Aug 12 '17 at 21:45