• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to force unique values in a column when inserting using Hibernate

 
Kjeld Sigtermans
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am using Hibernate combined with HSQLDB. It has been a while since I used Hibernate.
Is it possible to have either Hibernate or HSQLDB make sure that rows in a table are unique?
I mean not just using a uniqueness constraint and getting an exception when persisting an object. When persisting an object, I would like one of these products to check if a similar row is already present in the table, and if so, use a reference to the already existing row, instead of the one that was about to be persisted.
Or do I first have to check this myself by retrieving all rows in a Set and then use contains(..), for the object and every child object?


Thanks!
Kjeld








 
Kjeld Sigtermans
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answering my own question:

I did not find any way that Hibernate will check if the object that I am about to persist somehow already is present in the database table.
So I created a method that recursively checks the object, and all its children, to see if either of them is already there in the database (comparing the columns that are defined to be unique). If so, the persisted 'table' row/object is used instead (replacing the object I was about to persist). If not, the new object is persisted.
I used a lot of Reflection to achieve this, but it works perfectly.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic