How can I know if Hibernate did an insert or update AFTER run getHibernateTemplate().saveOrUpdate(object);
the method is void!
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 or , and the version property value is the same value assigned to a newly instantiated object, save() it
- otherwise update() the object
I'm afraid I always have to check if the object already have a 'primary key/id' BEFORE run this method, is this the only way? If yes, how can I get the primary key/ID in a generic way?
Serializable id = session.getIdentifier(entity);
or Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity);
??
Yes, Checking the Identifier associated with an entity in the persistence context means we are checking if the entity is in persistent state or not. Since u have already referred the documentation i would suggest please have look at this question, Hibernate saveOrUpdate behavior - have a look at Olaf's answer, it explains how it works in short and sweet way.
with JPA 2.0 we have the
Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); way of checking.
However your question is tagged for hibernate, so the first one is correct.
Serializable id = session.getIdentifier(entity);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With