hibernate - 如何为特定类型的 NHibernate 查询添加默认 WHERE 条件

标签 hibernate nhibernate

我希望查询特定类型的所有查询默认包含 where 语句。

更准确地说,我有一个接口(interface) IIsTenantSpecific,带有属性 TenantId - 因此实体属于单个租户。

当我查询实现此接口(interface)的类型时,NHIberante 应该始终添加一个 WHERE 子句,过滤 TenantId。

NHibernate 中是否有一种机制(如拦截器或事件监听器)可以轻松实现此目的?

最佳答案

我想说,这种情况可以通过内置功能轻松覆盖:

18.1. NHibernate filters

类似Q & A

引用自文档:

NHibernate adds the ability to pre-define filter criteria and attach those filters at both a class and a collection level. A filter criteria is the ability to define a restriction clause very similiar to the existing "where" attribute available on the class and various collection elements. Except these filter conditions can be parameterized. The application can then make the decision at runtime whether given filters should be enabled and what their parameter values should be. Filters can be used like database views, but parameterized inside the application.

In order to use filters, they must first be defined and then attached to the appropriate mapping elements. To define a filter, use the <filter-def/> element within a <hibernate-mapping/> element:

<filter-def name="myFilter">
    <filter-param name="myFilterParam" type="String"/>
</filter-def>

Then, this filter can be attached to a class:

<class name="MyClass" ...>
    ...
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</class>

or, to a collection:

<set ...>
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</set>

因此,一旦我们定义了过滤器,并将其应用到我们的集合上 - 我们以后就可以随时轻松地在整个 session 中打开该过滤器:

session.EnableFilter("myFilter").SetParameter("myFilterParam", "some-value");

从那一刻起,每个集合都会通过所选列传递的“某些值”进行过滤

关于hibernate - 如何为特定类型的 NHibernate 查询添加默认 WHERE 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41094708/

相关文章:

java - 如何在 JPA 中构建插入查询

c# - IStatelessSession 多对一插入对象

c# - xxx 实例的标识符从 y 更改为 z

java - 评估 JPA 提供程序 : Market share of Hibernate/EclipseLink?

c# - WCF msmq 事务处理和工作单元

silverlight - NHibernate.Linq,WCF RIA 服务,奇怪的错误

C#,将 Xml 序列化与 Nhibernate 混合使用时出现问题

java - 如何使用连接池正确实现Hibernate连接工厂

hibernate - JPA/Hibernate 中 key 'PRIMARY' 的重复条目

java - hibernate native sql查询返回