Hi!
First of all, I'm using the JPA API for Hibernate.
I'm writing a servlet which needs to connect to one of many databases, depending on the request. Because of this, I'm using application-managed entity mangers and resource-local transactions.
To make it as quick as possible, I tried to create the EntityManagerFactory with all the common settings in init() and then only override connection details when creating the EntityManager in service():
Code:
// In init()
Map config = new HashMap(); // these could also be in persistence.xml
config.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
config.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
config.put("hibernate.connection.pool_size", "1"); // JDBC connection pool (use the built-in)
config.put("hibernate.current_session_context_class", "thread"); // Enable Hibernate's automatic session context management
config.put("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider"); // Disable the second-level cache
config.put("hibernate.show_sql", "true"); // Echo all executed SQL to stdout
EntityManagerFactory emf = Persistence.createEntityManagerFactory("InstancePU", config);
// In service() (executed many times)
Map configOverrides;
configOverrides = new HashMap();
configOverrides.put("hibernate.connection.url", "jdbc:mysql://server/database");
configOverrides.put("hibernate.connection.username", "user");
configOverrides.put("hibernate.connection.password", "pass");
EntityManager em = emf.createEntityManager(configOverrides);
// .. do stuff
em.close();
// In destroy()
emf.close();
Unfortunately, I can't create an EntityManagerFactory without a connection ("The user must supply a JDBC connection") and even if I do connect to some database,
the overrides don't seem to work at all to change it later (I don't know whether no properties can be overridden or just connection ones. Can't find it anywhere in the documentation).
I think the second issue (ignoring properties) is also a problem with Hibernate. It should at least throw an exception, not just silently swallow them.
Creating a new EntityManagerFactory on each request is a no-go, as it takes a LONG time to initialize.
Any ideas on how to tackle this problem?