user443854
user443854

Reputation: 7453

Hibernate: save if not already in the table

I have a table with several columns. Primary key is id, auto-generated.

Consider this code, which can be executed more than once:

  session.save(x);

The object x has the same contents, say if we run the program twice without any changes. As a result, the object appears twice in the table with different ids.

How can I modify this code to avoid duplicate insertions?

I considered using session.get, but that requires the knowledge of id.

I also considered setting up criteria from all fields of x other than id, but this is asking for trouble: one day I will add another column and forget to add it to criteria. Is there a good solution to this?

Upvotes: 0

Views: 57

Answers (1)

Paul U
Paul U

Reputation: 681

if you do a

YourObject cachedX = (YourObject)session.merge(x);

cachedX will now have the generated Id. Obviously you'll have to keep it around and you will most likely still need to come up with duplication rules.

Upvotes: 1

Related Questions