开发者

Dynamicly select datasource for entities runtime

I have an entity bean that will represent an expected result over multiple databases/datasources and can also be different queries executed, but same result always comming back. So the bean is re-used over different datasources that should be able to be dynamicly selected.

Is it possible with JPA to select during runtime the data source to be used to execute a query, and return the same type of entity bean? Also, does my ejb/application need to define the datasources that will be use开发者_运维问答d? Or can I always specify via jndi what datasource to use? Modifying the descriptor's and re-deploying an application everytime a new datasource is created is not an option.

Sorry if the question does not make 100% sense, rather difficult to get the idea through.


Is it possible with JPA to select during runtime the data source to be used to execute a query, and return the same type of entity bean?

You can't change the datasource of a persistence unit at runtime. However, you can configure several persistence unit and use one or another EntityManagerFactory. Maybe JPA is not the right tool for your use case.

Modifying the descriptor's and re-deploying an application everytime a new datasource is created is not an option.

And how will the application be aware of the "available datasources"?


You can change the JPA datasource at runtime, but the approach is tricky (introspection, JPA implementation specific, ...).

I've implemented my own implementation of javax.persistence.spi.PersistenceProviderwhich override the org.hibernate.ejb.HibernatePersistence and sets the datasource in both the Map and PersistenceUnitInfo of the PersistenceProvider just before creating the EntityManagerFactory. This way, my EntityManagerFactory has a datasource which has been configured at runtime. I keep my EntityManagerFactory until the application is undeployed.

You could use the same be approach and create N different EntityManagerFactory, each with its specific datasource. However keep in mind that each ÈntityManagerFactory uses a lot of memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜