I need to make hibernate to save only unpersisted objects. If this object is already persisted, hibernate must do nothing or ruturn the id of persisted object. Of cource equals() and hashCode() methods are owerriden and working fine.
Can I do it somehow via configuration or something like pre insert listener?
For example:
session.beginTransaction();
ElementToPersist element = new ElementToPersist();
element.setName("Element");
element.setValue("Value");
session.save(element);
session.getTransaction().commit();
session.beginTransaction();
ElementToPersist element2 = new ElementToPersist();
element2.setName("Element");
element2.setValue("Value");
session.save(element2);
session.getTransaction().commit();
In my case the both elements will be persisted with different id’s. How can i make hibernate to check the existance of this element before inserting? Can you show the best pratice?
Thank you.
Check if the elements exist in the database using a query, and insert it only if it doesn’t exist. Note that this should be enforced by a database constraing, because you might have a race condition if two transactions check and insert the same element concurrently.