我在 MySql 数据库中有一个表,带有 datetime
field 。这在 hbm.xml
中映射到我的域对象具有类似于以下属性的文件:
<property name="StartDate" column="datStartDate" not-null="true" type="datetime"/>
一切正常,除了 MySql 不存储 DateTime 字段的毫秒部分。但是,我不介意,我希望更新域对象以具有存储在数据库中的确切值。我希望能够在用于保存域对象的同一 session 中执行此操作。
这可能吗?
最佳答案
一个简单的方法是执行 session.Refresh(entity),但这会导致额外的查询。
在拦截器中可以工作,只是看起来很重。
http://www.nhforge.org/doc/nh/en/index.html#objectstate-interceptors (11.1)
你会想要这样的东西:
public override bool OnFlushDirty(object entity,
object id,
object[] currentState,
object[] previousState,
string[] propertyNames,
IType[] types)
{
if(entity is DomainObjectICareAbout)
for ( int i=0; i < propertyNames.Length; i++ ) {
if ( currentState[i] is DateTime ) {
DateTime dt = (DateTime)currentState[i];
dt = dt.AddMilliseconds(-1 * dt.Millisecond);
return true;
}
}
}
return false;
}
OnSave() 也是一样。
在自定义 IUserType 中执行此操作可能会更好,但我不确定用户类型公开执行此操作的能力吗?
比如 IUserType:
public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
{
DateTime dt = (DateTime)value;
dt = dt.AddMilliseconds(-1 * dt.Millisecond);
NHibernateUtil.DateTime.NullSafeSet(cmd, dt, index);
}
我不知道...我不确定最佳答案。只是提供想法。可能有更好的方法!
关于mysql - 使用 NHibernate 在 MySql 数据库中的域对象中进行日期时间解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1159004/