views:

133

answers:

1

Consider having an application using DataNucleus with the following persistence structure:

You have a class that has two attributes like created (Date) and lastUpdate (Date): How do you automatically fill those attributes with the appropriate values when an object of this class is going to be committed? Appropriate values would be setting both, created and lastUpdate to the current time when an object is inserted into the database and just updating lastUpdate when it has changed.

A: 

I figured it out myself now.

You need to create an InstanceLifecycleListener...

public class BasicEntityLifecycleListener implements StoreLifecycleListener {

    public void postStore(InstanceLifecycleEvent evt) {
    }

    public void preStore(InstanceLifecycleEvent evt) {
     if((PersistenceCapable)evt.getSource() instanceof BasicEntity) {
      BasicEntity obj = (BasicEntity)evt.getSource();
      Date now = new Date();
      if(JDOHelper.isNew(obj))
       obj.setCreated(now);
      obj.setLastUpdate(now);
     }
    }
}

and then register it within you PersistenceManager...

PersistenceManager pm = pmf.getPersistenceManager();
pm.addInstanceLifecycleListener(new BasicEntityLifecycleListener(), null);

I found the solution in the DataNucleus Access Plaftorm manual which I didn't have recognized until now. The online manual seems a bit complex to me.

Markus Lux