How to Retrieve Mapping Table Name for an Entity in JPA At Runtime

How to retrieve mapping table name for an entity in JPA at runtime?

If no table annotation is present (and no ORM.xml) then in JPA the table name is formed based on the class name (see the JPA spec). Hence why exactly do you need an accessor method ?

See http://www.datanucleus.org/products/accessplatform_2_0/jpa/orm/datastore_identifiers.html

How to retrieve an entity in JPA by table name at runtime?

I guess it strongly depends on JPA which you're using.

In JPA 2.0 you have class: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManagerFactory.html

This class has getMetamodel() method which I expect to contains all information about your database.

In Metamodel (http://docs.oracle.com/javaee/6/api/javax/persistence/metamodel/Metamodel.html) you have getEntities() that's how we get: EntityType

I'm not sure how get from EntityType information about table it is using. But even it's not directly possible (which I doubt) you can do it as described below.

Because you have legacy code I expect you have JPA < 2.0 which doesn't have this getMetamodel method. That's why informations you can get about entities strongly depends on specific JPA you're using.

However if you have bunch of classes you care about (and you can create this list easily) you can create index on your own:

String tableNameOfEntityClass = LanguageEntity.class.getAnnotation(Table.class).name();

So you can put all classes you care to list and then create map with key tableName and value refering class.

Of course it's not very useful without Metamodel which I described above because as well you can create ready map instead of List with entity classes.

Code example to retrieve table name for an entity in JPA in runtime?

OK, so if want do this with reflection. It should be pretty easy since this runtime class have to extends your class. If it wouldn't extends your class you won't be able to use it in your application.

So you have to do something like below

    String myPackage = "com.company.";
Class entityClass = y.getClass();
while (!entityClass.getCanonicalName().startsWith(myPackage)) {
entityClass = entityClass.getSuperclass();
}
Class classInYourPackage = entityClass;

And you should get correct (your) class.

Not tested, however that's the way it should work.

EDIT: Not sure what package will be assigned by JPA to these runtime classes. So if code above doesn't work try with getSuperclass() method on your own.

How do I configure JPA table name at runtime?

For Hibernate 4.x, you can use a custom naming strategy that generates the table name dynamically at runtime. The server name could be provided by a system property and so your strategy could look like this:

public class ServerAwareNamingStrategy extends ImprovedNamingStrategy {

@Override
public String classToTableName(String className) {
String tableName = super.classToTableName(className);
return resolveServer(tableName);
}

private String resolveServer(String tableName) {
StringBuilder tableNameBuilder = new StringBuilder();

tableNameBuilder.append(tableName);
tableNameBuilder.append("_");
tableNameBuilder.append(System.getProperty("SERVER_NAME"));

return tableNameBuilder.toString();
}
}

And supply the naming strategy as a Hibernate configuration property:

<property 
name="hibernate.ejb.naming_strategy"
value="my.package.ServerAwareNamingStrategy"
/>

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.

Change Table Name of an Entity on runtime?

Is it possible to change the table name of an entity as follows on runtime since they have the same table structure after all?

This is not really possible, at least not with standard JPA (which doesn't mean I did it with non standard JPA) as mentioned in questions such as:

  • In @Table(name = “tableName”) - make “tableName” a variable in JPA
  • JPA: How do I specify the table name corresponding to a class at runtime?
  • Hibernate or iBatis or something else?

To summarize, JPA doesn't offer a way to "alter" a given entity of an already initialized persistence unit (and the related pre-compiled CRUD queries, the pre-compiled named queries, etc).

Still, since you're using Hibernate, maybe have a look at http://www.hibernate.org/171.html to get an idea of what would be possible using Hibernate Core API.

Another option I can think of would be to use a database synonym / alias: FOO would be an alias for FOO_JAN2010 until... you change the alias to point on FOO_FEB2010. I've never tested this, I don't know if it will suit your needs. But it's another idea.



Related Topics



Leave a reply



Submit