开发者

Hibernate DefaultSaveOrUpdateEventListener checking for insert and update database events

Using hibernate 3.3.2.ga and Spring 3.0.5.RELEASE.

Have implemented something as described here..

with a different config as I;m using a Spring managed sessionFactory

<bean id="sessionFactoryPGAD" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSourcePGAD"/>
.......
.......
<property name="eventListeners">
    <map>
        <entry key="save-update"><ref local="auditEntityListener" /></entry>
    </map>
</property>

to add auditing when my DAOs call

...getCurrentSession().saveOrUpdate(...

However in my extended DefaultSaveOrUpdateEventListener (bean named auditEntityListener) I was wondering if there is any way to determine if the object being saved to the db is a new record or an update to one that exists?

I've tried looking at

EntityEntry entityEntry = event.getEntry();
if (entityEntry.isExistsInDatabase())
{.....

but entityEntry is null for an entity I know exists in the db.

Other methods on SaveOrUpdateEvent like getRequestedId() and getResultId() also return null.

How could I determine if the hibernate call will be 开发者_运维知识库a insert or update from the DefaultSaveOrUpdateEventListener?


The method you're looking for is getEntityState(). Here's an example of its use taken from the source code for DefaultSaveOrUpdateEventListener:

int entityState = getEntityState(
    event.getEntity(),
    event.getEntityName(),
    event.getEntry(),
    event.getSession()
);

switch ( entityState ) {
    case DETACHED:
        entityIsDetached( event );
        return null;
    case PERSISTENT:
        return entityIsPersistent( event );
    default: //TRANSIENT or DELETED
        return entityIsTransient( event );
}

If you need to do something different for save versus update, you might want to consider having separate EventListeners, one that extends DefaultSaveEventListener and one that extends DefaultUpdateEventListener, and allow Hibernate to dispatch to the correct listener for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜