您的位置:首页 > 其它

Castle ActiveRecord 应用 Expression.Example 模板对象匹配查询

2006-03-30 13:26 405 查看
Hibernate (NHibernate) 提供了一种称为 Example 的检索对象的方法。该方法提供了根据模板对象匹配检索目标对象的解决方案。模板对象和目标对象的对象类型是相同的,只要开发人员给模板对象指定了个别属性的值,Hibernate/Nhibernate 就会根据这些模板属性在数据库中检索匹配的数据对象。不仅如此,Example 更允许通过扩展方法对模板对象的属性实施约束,使检索更加灵活。

NHibernate 从 0.8.2 版本开始支持这种方法。

详情请使用 VS.NET 对象浏览器查看 NHibernate.Expression.Example 的摘要信息,或参考 Hibernate 的相关文档。

特别地,以下网址收录了相似的用法:

主站:http://www.koders.com/Default.aspx?s=hibernate&p=10
链接:http://www.koders.com/java/fid9F29DE483511B282CFECD9E9522EA01EEF2648CF.aspx?s=hibernate

查询方法代码:

/// <summary>
/// 获取一个与参数帐户匹配的帐户
/// </summary>
/// <param name="account">被匹配的帐户实例</param>
/// <returns>结果帐户实例 或 null</returns>
public static Account Find(Account account)
{
Account result = (Account) FindFirst( typeof(Account), new Example[]
{
Example.Create(account)
});
return result;
}
测试用例:

[Test]
public void AccountFindTest()
{

Assembly assembly = typeof(Account).Assembly;
XmlConfigurationSource src = new XmlConfigurationSource(assembly.GetManifestResourceStream("StephenCat.WebFolder.Domain.ActiveRecord.config"));
ActiveRecordStarter.Initialize( src, typeof(Account), typeof(Role), typeof(Resource) );

// 注意:由于存在关联,这里要初始化两个实体。
// 否则会抛出 unmapped: Post 的 Exception。

Account account = new Account();

account.Name="admin";
account.Password="789456123";

Account result = Account.Find(account);

Console.WriteLine(result.Name);

}

输出结果:

------ Test started: Assembly: StephenCat.WebFolder.dll ------

admin

1 passed, 0 failed, 0 skipped, took 2.20 seconds.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: