我有一个Hibernate拦截器,我想将其置于Hibernate的onLoad()调用中。我这样做是因为我希望JPA实体具有一个由Spring注入到其中的SecureRandom实例。由于JPA上下文和Spring上下文没有混合使用,因此这是从Spring上下文到JPA上下文的桥梁。
我在Java配置中有“两个地方”,为Hibernate 4设置了东西。我在下面包括了它们的输入项。据此(https://jira.springsource.org/browse/SPR-8940),我认为要以编程方式设置Hibernate拦截器,我需要访问LocalSessionFactoryBean。也许通过LocalContainerEntityManagerFactoryBean?我只是不知道该怎么做,或者是否需要重新配置我的Hibernate东西的方式。任何帮助将非常感激!
@Bean
JpaTransactionManager jpaTransactionManager(LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(localContainerEntityManagerFactoryBean.getObject());
return jpaTransactionManager;
}
@Bean(name = "LocalContainerEntityManagerFactory")
@Autowired
public LocalContainerEntityManagerFactoryBean entityManagerFactory(BasicDataSource jdbcConnection) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class.forName("com.mysql.jdbc.Driver").newInstance();
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(jdbcConnection);
localContainerEntityManagerFactoryBean.setPackagesToScan(this.getClass().getPackage().getName());
Properties jpaProperties = new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "create");
localContainerEntityManagerFactoryBean.setJpaProperties(jpaProperties);
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
hibernateJpaVendorAdapter.setShowSql(true);
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter);
return localContainerEntityManagerFactoryBean;
}
@Component
public class InvitationEntityInterceptor extends EmptyInterceptor {
@Autowired
SecureRandom secureRandom;
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
if(entity instanceof Invitation) {
Invitation invitation = (Invitation) entity;
invitation.setRandom(secureRandom);
}
return false;
}
}
我放弃了使用一些基于休眠特定于事件的解决方案的方法,而是选择使用@Configuration,它在Spring中需要AspectJ。
参见http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/aop.html
9.8.1使用AspectJ通过Spring依赖注入域对象
Spring容器实例化并配置在您的应用程序上下文中定义的bean。给定包含要应用的配置的Bean定义的名称,也可以要求Bean工厂配置预先存在的对象。spring-aspects.jar包含一个注释驱动的方面,该方面利用此功能允许任何对象的依赖项注入。该支架旨在用于在任何容器的控制范围之外创建的对象。域对象通常属于此类,因为它们通常是使用new运算符或数据库查询的结果通过ORM工具以编程方式创建的。
@Configurable注释将一个类标记为符合Spring驱动的配置。在最简单的情况下,它可以用作标记注释:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句