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

You need to use the XML version of the configuration rather than the annotations. That way you can dynamically generate the XML at runtime.

Or maybe something like Dynamic JPA would interest you?

I think it’s necessary to further clarify the issues with this problem.

The first question is: are the set of tables where an entity can be stored known? By this I mean you aren’t dynamically creating tables at runtime and wanting to associate entities with them. This scenario calls for, say, three tables to be known at compile-time. If that is the case you can possibly use JPA inheritance. The OpenJPA documentation details the table per class inheritance strategy.

The advantage of this method is that it is pure JPA. It comes with limitations however, being that the tables have to be known and you can’t easily change which table a given object is stored in (if that’s a requirement for you), just like objects in OO systems don’t generally change class or type.

If you want this to be truly dynamic and to move entities between tables (essentially) then I’m not sure JPA is the right tool for you. An awful lot of magic goes into making JPA work including load-time weaving (instrumentation) and usually one or more levels of caching. What’s more the entity manager needs to record changes and handle updates of managed objects. There is no easy facility that I know of to instruct the entity manager that a given entity should be stored in one table or another.

Such a move operation would implicitly require a delete from one table and insertion into another. If there are child entities this gets more difficult. Not impossible mind you but it’s such an unusual corner case I’m not sure anyone would ever bother.

A lower-level SQL/JDBC framework such as Ibatis may be a better bet as it will give you the control that you want.

I’ve also given thought to dynamically changing or assigning at annotations at runtime. While I’m not yet sure if that’s even possible, even if it is I’m not sure it’d necessarily help. I can’t imagine an entity manager or the caching not getting hopelessly confused by that kind of thing happening.

The other possibility I thought of was dynamically creating subclasses at runtime (as anonymous subclasses) but that still has the annotation problem and again I’m not sure how you add that to an existing persistence unit.

It might help if you provided some more detail on what you’re doing and why. Whatever it is though, I’m leaning towards thinking you need to rethink what you’re doing or how you’re doing it or you need to pick a different persistence technology.

Leave a Comment