Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Table Name of an Entity on runtime? [duplicate]

There is this table that is being generated on a monthly basis. Basically the table structure of all monthly tables is the same.

Since it would be a lot of work to map the same entity just with a different table name,

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

   @Entity
   @Table(name="FOO_JAN2010") // any other ways to generate this dynamically?
   public class FooJan2010Table {  // if we can dynamically set the table name this can be simply named FooTable
       ...
   }

If not, what approach can you suggest?

like image 259
Joopiter Avatar asked Oct 07 '10 07:10

Joopiter


2 Answers

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.

like image 182
Pascal Thivent Avatar answered Nov 03 '22 14:11

Pascal Thivent


You can probably do it using Naming Strategies if you use Hibernate as JPA provider. See my answer to this previous question for reference.

You should be able to design your naming strategy to return table names in a dynamic way.

The question whether you should do it that way is a completely different one, though.

Also, thanks Pascal for reminding me, this will only work if the EntityManagerFactory is recreated once per month (there are many ways to do that, restarting the webapp being the simplest one)

like image 5
Sean Patrick Floyd Avatar answered Nov 03 '22 12:11

Sean Patrick Floyd