I’m using Hibernate 4.0.1.Final. I have a table with a unique constraint column …
@Entity
@Table(name = "cb_contract",
uniqueConstraints = {@UniqueConstraint(columnNames={"ORDER_ID"})}
)
public class Contract {
...
@Column(name = "ORDER_ID")
private String orderId;
Currently, if I try and save two objects that have the same value for the order ID column, using the below method …
protected void saveOrUpdate(Object obj) {
final Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(obj);
}
I get a “org.hibernate.exception.ConstraintViolationException: integrity constraint violation: unique constraint or index violation” exception when saving the second instance. Is there a way I can make Hibernate save or replace objects based off the unique column or do I need to search for the object first, delete it if it is there, and then re-insert the one?
I think you’re correct, but the closest thing that matches what you’re trying to do is documented here – Can Hibernate work with MySQL's "ON DUPLICATE KEY UPDATE" syntax?
Depending on what it is you are trying to do, I would get concerned that you’d be happy to overwrite an existing record if one with the same key/constraint already exists.
I would prefer to remove the unique constraint altogether and grab the one with largest Id for that orderId instead. That way you can at least keep a backup copy of all the contracts with that orderId. This is obviously less efficient on memory space however.