Using saveOrUpdate() in Hibernate creates new records instead of updating existing ones
database, hibernate, java, orm
Solution
This code always trying insert bill to database , rather than update when row about Bill exists in DB...
From the section 10.7. Automatic state detection of the Hibernate core documentation:
`saveOrUpdate()` does the following:
- if the object is already persistent in this session, do nothing
- if another object associated with the session has the same identifier, throw an exception
- if the object has no identifier property, `save()` it
- if the object's identifier has the value assigned to a newly instantiated object, `save()` it
- if the object is versioned by a `<version>` or `<timestamp>`, and the version property value is the same value assigned to a newly instantiated object, `save()` it
- otherwise `update()` the object
When you do:
User bill = new User();
bill.setName("Bill");
session.saveOrUpdate(bill);
This newly created instance does not have any identifier value assigned and `saveOrUpdate()` will `save()` it, as documented. If this is not what you want, make the `name` the primary key.
Problem
I have a class User ``` class User { int id; String name; } ``` where `id` is native generator in `User.hbm.xml` and `name` is primary-key in DB. In my database I saved some information about Users. Than I want to connect with this information about User. For example in my DB I have a row `INSERT INTO User VALUES ('Bill');` Main.java ``` User bill = new User(); bill.setName("Bill"); session.saveOrUpdate(bill); ``` This code always tries to insert a new `Bill` row into the table rather than update the existing `Bill` row.