Chetan Khilosiya
Chetan Khilosiya

Reputation: 541

Getting hibernate persistent object at the time of pre update event

I am implementing pre update event listener in java hibernate 4.3. I need to get old persistent object value before update occures. I have tried using event.getOldState() in PreUpdateEventListener. But it gives Object[] as return type. I want the persistent object as return value.

How to get complete persistent object in preUpdateEvent? The preUpdateEventListener is implemented correctly. Just need to get Complete persisted object instead i get Object[].

Also tried event.getSession().get(id,persisted.class); //this gives new object as session has set new object to update

Below is code that gives Object[]

import org.hibernate.event.spi.PreUpdateEventListener;
import org.hibernate.event.spi.PreUpdateEvent;
public class MyEventListener implements PreUpdateEventListener  {
    public void onPreUpdate(PreUpdateEvent event)  {
        Object newEntity=event.getEntity();    //Gives new Object which will be updated.
        Object[] oldEntity=evetn.getOldState();    //gives old Object[] which can't be converted to persisted Object
        //Code here which will give me old persisted objects, hibernate fetches object in array format.
    }
}

Upvotes: 4

Views: 3961

Answers (2)

Gab
Gab

Reputation: 8323

If i remember well the object array contains all attribute values of given entity : the index of the associated property can be resolved using the property name array

 String[] propertyNames = event.getPersister().getEntityMetamodel.getPropertyNames();

this link may be usefull

Upvotes: 4

kostja
kostja

Reputation: 61538

I am not sure how listeners work with pure Hibernate, but if you use JPA event listeners, the entity is passed as a parameter to the listener method:

public class MyUpdateListener {

  @PreUpdate
  public void onPreUpdate(MyEntiy e) {
    e.getAttribute();
    // do something
  }
 ...

If you define a listener method inside the entity, you can simply access the state of this

@PreUpdate
public void onPreUpdate() {
  getAttribute();
  // do something
}

Upvotes: 0

Related Questions