我怎么知道Hibernate在运行getHibernateTemplate()之后是否进行了插入或更新.saveOrUpdate(object);方法无效!
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
我担心我总是要检查对象是否已经有’主键/ id’在运行此方法之前,这是唯一的方法吗?如果是,我如何以通用方式获取主键/ ID?
Serializable id = session.getIdentifier(entity);或Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); ??
最佳答案 是,检查与持久性上下文中的实体关联的标识符意味着我们正在检查实体是否处于持久状态.
既然你已经提到我建议的文件,请看看这个问题,
Hibernate saveOrUpdate behavior – 看看奥拉夫的答案,它解释了它如何以简短而甜蜜的方式运作.
我们有JPA 2.0
Object id = entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); way of checking.
但是你的问题被标记为休眠,所以第一个是正确的.
Serializable id = session.getIdentifier(entity);