Assuming you have a MyStatementInspectorwhich implements StatementInspector.
You can supply it at SessionFactory level:
Code:
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "org/hibernate/example/hibernate.cfg.xml" )
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" )
.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
// Supply an StatementInterceptor
sessionFactoryBuilder.applyStatementInspector( new MyStatementInspector() );
SessionFactory sessionFactory = sessionFactoryBuilder.build();
Or, as I explained in
this article, you could use the hibernate.session_factory.statement_inspector configuration property.
This way, it does not matter whether you are bootstrapping Hibernate using JPA (e.g. Spring Data JPA) or native Hibernate (e.g. Spring with HibernateTranscationManager and LocalSessionFactoryBean).
So, you can to provide the hibernate.session_factory.statement_inspector via the persistence.xml JPA configuration file:
Code:
<property
name="hibernate.session_factory.statement_inspector"
value="com.vladmihalcea.book.hpjp.hibernate.logging.inspector.SqlCommentStatementInspector"
/>
Or, you can also set the hibernate.session_factory.statement_inspector programmatically if you're using Spring:
Code:
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan({
"com.vladmihalcea.books.high.performance.java.persistence"
});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.session_factory.statement_inspector",
SqlCommentStatementInspector.class
);
hibernateProperties.setProperty(
"hibernate.dialect",
"org.hibernate.dialect.H2Dialect"
);
return hibernateProperties;
}
Notice that the hibernate.session_factory.statement_inspector setting can take either a String representing he fully-qualified class implementing the StatementInspector interface, a Class<? extends StatementInspector> or a StatementInspector object reference.