Is there a way to check if the Hibernate.saveOrUpdate () method has been inserted or updated?

How to find out if Hibernate has been inserted or updated AFTER running getHibernateTemplate().saveOrUpdate(object); , the method is invalid!

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 does not have an identifier property, save () it
  • if the object identifier has the value assigned to the newly created object, save () it
  • if the object has a version using a or, and the value of the version property is the same value assigned to the newly created object, save () it
  • otherwise update () the object

I'm afraid that I always need to check if the object already has a "primary key / identifier" before running this method - is this the only way? If so, how can I get the primary key / identifier in a general way?

Serializable id = session.getIdentifier(entity); or Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); ??

+4
source share
1 answer

Yes, checking the identifier associated with the entity in the context of persistence means that we check whether the object is in a constant state or not. Since you have already specified the documentation, I would suggest, please look at this question, Hibernate saveOrUpdate behavior - take a look at Olaf's answer, he explains how this works in a short and sweet way.

with jpa 2.0 we have

Object id = entityManagerFactory.getPersistenceUnitUtil (). getIdentifier (entity); verification method.

However, your question is flagged for sleep mode, so the first one is correct.

Serializable id = session.getIdentifier (entity);

+2
source

Source: https://habr.com/ru/post/1487096/


All Articles