hibernatejakarta-eejpajpa-2.0java-ee-6

Merging entity with a unique constraint


I have an entity similar to:

@Entity
@Table( name="marchi", uniqueConstraints=@UniqueConstraint(columnNames="codice") )
public class Marchio implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    private String codice;

    private String nome;
//...
}

I create a Marchio with codice = 123, then I persist it. OK!

Then I retrieve it from the DB via a query, edit the "nome" property with something and call merge(). OK!

Then I create another Marchio with codice = 123. I put something in nome and call merge().

Result is:

ConstraintViolationException: Duplicate entry '123' for key 'codice'

Good, actually I can use the first way: query, edit property nome and merge.

Consider I don't have only "nome". I have 35 different properties, so I don't want to:

Marchio m = em.findCodice("123");
m.setP1("1");
m.setP2("2");
...
m.setPN("N");
em.merge(m); 

How can I do?


Solution

  • If I've understood well, you already have a detached object with updated values and you don't want to retrieve the corresponding object from the db and update it calling many set methods. The only way to accomplish this is to remove the old object and then persist the detached new object:

    em.remove(oldobj);
    em.persist(newobj);