4

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?

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

2

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.

Community
  • 1
  • 1
Dedawn
  • 80
  • 4
  • 1
    With regards to the "DUPLICATE KEY UPDATE" syntax, can it mimic MySQL's REPLACE INTO syntax -- http://dev.mysql.com/doc/refman/5.0/en/replace.html ? That is ultimately what I want to do. I tried putting the "REPLACE" sql statement into the @SQLInsert annotation but got an error saying Hibernate didn't recognize the "REPLACE" token. – Dave Jun 27 '12 at 15:24
  • 1
    Take a look at - http://stackoverflow.com/questions/11235501/mysql-insert-row-on-duplicate-key-update-multiple-columns @Dave – Dedawn Jun 27 '12 at 23:15