从Spring Boot 2.0.0 M2升级到2.0.0 M6后,我的Hibernate拦截器实现不再起作用了。
我的旧实施:
@Configuration
public class HibernateConfiguration extends HibernateJpaAutoConfiguration {
private HibernateStatisticsInterceptor hibernateStatisticsInterceptor;
public HibernateConfiguration(DataSource dataSource, JpaProperties jpaProperties, ObjectProvider<JtaTransactionManager> jtaTransactionManager, ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers, ObjectProvider<List<SchemaManagementProvider>> providers, HibernateStatisticsInterceptor hibernateStatisticsInterceptor) {
super(dataSource, jpaProperties, jtaTransactionManager, transactionManagerCustomizers, providers);
this.hibernateStatisticsInterceptor = hibernateStatisticsInterceptor;
}
@Override
protected void customizeVendorProperties(Map<String, Object> vendorProperties) {
vendorProperties.put("hibernate.session_factory.interceptor", hibernateStatisticsInterceptor);
}
}
但是对于M5或M6,HibernateJpaAutoConfiguration类已经改变并且不再扩展JpaBaseConfiguration。
我尝试按YAML配置文件添加拦截器,但它无效。
我的拦截器:
@Component("hibernateStatisticsInterceptor")
public class HibernateStatisticsInterceptor extends EmptyInterceptor {
private static final long serialVersionUID = 5278832720227796822L;
private ThreadLocal<Long> queryCount = new ThreadLocal<>();
public void startCounter() {
queryCount.set(0l);
}
public Long getQueryCount() {
return queryCount.get();
}
public void clearCounter() {
queryCount.remove();
}
@Override
public String onPrepareStatement(String sql) {
Long count = queryCount.get();
if (count != null) {
queryCount.set(count + 1);
}
return super.onPrepareStatement(sql);
}
}
如何重新激活我的拦截器?
感谢任何提示
问候 Rizzi的
答案 0 :(得分:5)
你好,
将其读为:https://github.com/spring-projects/spring-boot/commit/59d5ed58428d8cb6c6d9fb723d0e334fe3e7d9be(使用:HibernatePropertiesCustomizer接口)
希望这对您有用。
最后一点:总是更新您的Spring / Hibernate版本(尽可能使用最新版本),随着新版本尝试尽可能减少配置,您将看到大多数代码将变得多余。可能。
答案 1 :(得分:4)
由于https://github.com/spring-projects/spring-boot/issues/11211已经解决,因此可以使用HibernatePropertiesCustomizer
,因为Spring Boot 2.0.0.RC1(目前尚未发布,但现在可以使用快照)。
答案 2 :(得分:3)
我可以通过此文档解决此问题:
Add support for advanced customization of Hibernate settings
只需实现一个接口 HibernatePropertiesCustomizer
并实现方法 customize(Map hibernateProperties)
@Component
class MyHibernateInterceptorCustomizer implements HibernatePropertiesCustomizer {
@Autowired
MyInterceptor myInterceptor
@Override
@Override
void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put("hibernate.session_factory.interceptor", myInterceptor);
}
}