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
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
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.
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);
I used HQL and it worked
entity.setLastUpdate((Date) session.createSQLQuery(
"select getdate()").list().get(0))