Search code examples
javahibernatejpaormhibernate-mapping

How to set a Hibernate interceptor for an EntityManagerFactory


I'm using JPA, but I need to unwrap my EntityManagerFactory, so I can add an interceptor to the Session. Afterward I want to wrap the Session back to a EntityManager.

"Why not just use Session instead of EntityManager?" We still want to reduce the impact of a possible technology migration

For what do I want to use Interceptor:

I can resume the problem in the following way: The project works running queries on a alarms database. Each place has one database with a Alarm Table, but the client wants to have a single database, where we will have to create multiple "Alarm Table", one for each place (ex: Table_Alarm-Place1, Table_Alarm-Place2). That means we would have multiple tables for the same entity, the interceptor has the goal of changing the Table name generate by hibernate in the final SQL

How I pretend to use the interceptor:

public class SqlInterceptor extends EmptyInterceptor {

    private String tableSufix;

    private static final Logger LOGGER = LoggerFactory.getLogger(SqlInterceptor.class);

    public SqlInterceptor(String tableSufix) {...}

    @Override
    public String onPrepareStatement(String sql) {
        String finalSql;

        //Manipulated SQL (parsed by Hibernate)

        return finalSql;
    }

}
  • The project uses JPA 2.1 and Hibernate 4.3.11.Final

Solution

  • You can store all the necessary information in a static ThreadLocal instance and read it afterwards.

    This way you avoid the complications with session scoped interceptors and you can use other mechanisms to achieve the same goal (for example with a session factory scoped interceptor which is a bit easier to configure).