Modify JPA schema at runtime with EclipseLink runn

2019-08-07 11:42发布

问题:

I am new to JPA and JBoss, so sorry in advance if this is a stupid question.

I have application running on JBoss using EclipseLink that retrieves entities from various databases based on a JPQL string. This is working great, except one database contains multiple schema's. I would like to be able to specify which schema to use, at runtime, and select all entities that belong to that schema, without modifying the JPQL string.

To further complicate things, I would also like to join across schema's, in the same query. In this case, the JPQL query could change, or parameters could be set which specifies each entities schema.

After some searching I came across this:

JPA: How do I specify the table name corresponding to a class at runtime?

Which has a solution using ASM that dynamically modifies the Table annotation. I have tried to use this to modify the Table annotation's schema property but for the life of me I cannot get it to work; it seems that Eclipse Link uses a different class loader to init the entity classes that I don't know how to access and thus changing the annotation has no effect.

Another solution is have multiple xml configuration files for each schema. It seems inelegant; when I add a new entity I have to remember to add it to every schema's xml file. I also do not know how I can make this join across multiple schema's.

Is there any way of solving this problem? Am I missing something or is this pushing JPA beyond what it was intended for?

回答1:

You should have a different persistence unit per schema. You can use the same classes/mappings, you would just need an orm.xml file that defines the different default schema. The file doesn't need anything else in it, you can still map your objects in annotations, or in a separate orm.xml file.

To have a persistence unit with some objects in one schema, and some in another, you again could do this in an orm.xml file. You will just need to include the entities that use the non-default schema in the orm.xml file. EclipseLink always merges annotations and XML, so you can use both and only have the additions you need in xml.

EclipseLink also allows you to set a tableQualifier which defines the default schema. This can be set using a SessionCutsomizer on the Session's login.