相关疑难解决方法(0)

如何为sessionFactory.getCurrentSession()启用hibernate过滤器?

假设有一个带有结构的User表:

用户

  • 项目清单
  • userId(PK)
  • 公司(PK)
  • 用户名
  • 地址......等

我想只检索当前公司的用户(公司可以由用户通过UI更改,因此公司是运行时参数)

类似地,还有许多其他表与公共列(公司)具有相似的结构,我想将数据限制为仅当前公司,因此我使用hibernate过滤器来过滤数据.

Hibernate注释:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">Dialect....</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.generate_statistics">true</prop>
            <prop key="hibernate.connection.release_mode">after_transaction</prop>
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>User</value>
        .....
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

过滤器定义:

@org.hibernate.annotations.FilterDef(name="restrictToCurrentCompany",
    parameters = {@org.hibernate.annotations.ParamDef(
            name = "currentCompanyNumber", type = "int"
        )
    }
)
@Entity
@Table(name = "USER")
@org.hibernate.annotations.Filter(
        name = "restrictToCurrentCompany",
        condition="company = :currentCompanyNumber"
)
public class User implements Serializable {
    private int company;
    private String userName; …

spring hibernate hibernate-annotations hibernate-filters

9
推荐指数
1
解决办法
2万
查看次数

使用Spring AOP配置Hibernate会话

我有一个Spring Framework 4应用程序,它使用Hibernate 4.3.8作为JPA提供程序.我想使用Hibernate过滤器,因此我需要启用它们.我想在应用程序中全局执行此操作,我正在尝试使用Spring AOP.我的想法是,我可以编写一个方面,每次创建/获取会话时启用过滤器,就像在这个这个问题中一样.

我已将spring-aopaspectjweaver依赖项添加到我的项目中(使用Maven).我添加了以下方面.

@Aspect
@Component
public class EnableHibernateFilters {
    @Pointcut("execution(* org.hibernate.SessionFactory.getCurrentSession(..))")
    protected void sessionBeingFetched() {

    }

    @AfterReturning(pointcut = "sessionBeingFetched()", returning = "object")
    public void enableFilters(JoinPoint joinPoint, Object object) {
        System.out.println("!!! Enabling filters !!!"); // Never printed

        Session session = (Session) object;
        session.enableFilter("myFilter");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是enableFilters从不调用上面的advice(); 既没有打印文本,也没有启用我的过滤器.我已经通过将切入点更改为我自己的一个类来验证我的方面已被检测到并且AOP在我的项目中有效.我也尝试将切入点更改为execution(* org.hibernate.SessionFactory.openSession(..)),但没有结果.

我怀疑这是由我如何设置Hibernate引起的,因为我没有SessionFactory明确配置; 相反,我建立了一个EntityManagerFactory.这是我的配置.

@Configuration
@EnableTransactionManagement
public class PersistenceConfig {
    @Bean
    public DataSource dataSource() throws NamingException …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate spring-aop

8
推荐指数
1
解决办法
3193
查看次数