views:

45

answers:

3

Hi,

I would like to add db server's timestamp in last_update column of my table. How can I achieve this in hibernate?

Thanks

+1  A: 

This isn't a pretty solution but it works. Use the formula property.

<property name='ServerDate' formula='getdate()'/>

Place that field in some kind of dummy entity and you'll be able to pull the date from your SQL database and from there you can assign it to your last_update column.

I've done quite a bit of searching and I haven't found an easier way to do this.

Spencer Ruport
Thanks for your answer, does it mean that I can't have ServerDate as one of the property for object being saved and I have to use dummy entity?
Vishal
You can but you'll still have to assign it. I only recommended the dummy entity because it could be misleading to have that field as a property of a real entity.
Spencer Ruport
Ok, I am new to hibernate do I have to create configuration file for that dummy entity? How do I get ServerDate and later assign it back to last_update field?
Vishal
Yes create a configuration file like you normally would. Point it to some arbitrary table and do all the normal work you'd do to retrieve an instance. Once you have the object this property will be populated with the SQL server's date and you can assign it to the last_update property of the entity you're working with.
Spencer Ruport
Can't we get the db date from the hibernate-sql and use it?
Vishal
A: 

You can create a new SaveOrUpdateEventListener:

public class DateTimeSaveOrUpdateEventListener : DefaultSaveOrUpdateEventListener
{
    protected override object EntityIsPersistent(SaveOrUpdateEvent @event)
    {
        MyEntity ent = @event.Entity as MyEntity;
        if(ent != null)
            ent.LastUpdate = DateTime.Now;
        return base.EntityIsPersistent(@event);
    }

    protected override object EntityIsTransient(SaveOrUpdateEvent @event)
    {
        MyEntity ent = @event.Entity as MyEntity;
        if(ent != null)
            ent.LastUpdate = DateTime.Now;
        return base.EntityIsTransient(@event);
    }
}

and register it in your configuration like this:

var listener = new DateTimeSaveOrUpdateEventListener();
config.SetListener(NHibernate.Event.ListenerType.SaveUpdate, listener);
config.SetListener(NHibernate.Event.ListenerType.Save, listener);
snicker
A: 

I used HQL and it worked

entity.setLastUpdate((Date) session.createSQLQuery(
        "select getdate()").list().get(0))
Vishal