Skip to content
Advertisement

How to insert data in multiple tables if tables have relationship OneToMany, and @Column(unique = true)

I have two tables MAKES and MODELS. Between them relationship @ManyToOne.

Table MAKES:

@Column(unique = true)
private String make;

Table MODELS:

@Column(unique = true)
private String model;

When I insert schema car:

makes.setMake("Porsche");
models.setModel("911");

em.persist(makes);
em.persist(models);

Data is added, but if Porsche exist in MAKES table an exception is returned: ... Duplicate entry 'Porsche' for key ....

Advertisement

Answer

This constraint violation error is supposed to happen to prevent you from accidentally doing what you are doing here – inserting two separate Make instances that both have the Make column value of “Porsche”. If you need to have multiple Makes with the value “Porsche”, you need to relax the constraint to allow duplicates.

What seems more likely is this is intended, and you have an existing Make that you want to associate to or under a new Model. Read in the existing make from the DB and use that managed instance within your EntityManager context instead of trying to persist a new Make instance.

Ie

  Query q = em.createQuery("select m from Make m where m.make = 'Porsche'");
  Make Porsche = q.getSingleResult();
  models.setModel("911");
  models.setMake(Porsche);
  em.persist(models);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement