s.grinovero wrote:
all managed objects need to have assigned a primary key before it can be added to the persistence context.
I guess you're using a type of primary key which is generated by the database (like mysql autoincrements?) so Hibernate needs to send the INSERT statement to the database in order to have a PK assigned. This doesn't change semantics as of course using the transaction is still needed, as you are still able to rollback the database transaction until the call to commit(); it might be interesting to consider this for performance tuning, but your code should behave the same way.
I got another problem because of that behavior. When I use em.merge() to save a record. Hibernate always send an insert statement to database first which fails every time because of duplicate unique key.
So in order to save a record, instead of one line em.merge(entity), I have to do something like this:
public void save(MobileAppOwner entity) {
try {
MobileAppOwner existingEntity = this.find(entity.getMobileApp(), entity.getPerson());
existingEntity.setMobileApp(entity.getMobileApp());
existingEntity.setPerson(entity.getPerson());
existingEntity.setStatus(entity.getStatus());
existingEntity.setLastUpdatedTime(entity.getLastUpdatedTime());
em.merge(entity);
} catch (javax.persistence.NoResultException e) {
em.persist(entity);
}
}
What is the best practice to solve this problem? This has been bothering me for months, any help will be greatly appreciated.