As far as I can see, there can't be an easy solution for this. Even if Hibernate mapping files allowed you to describe two different mappings, there are so many situations in which Hibernate, explicitly or implicitly, has to write objects of that class -- so how should it decide which table to use? Your requirement to first use table1, then table2, can only be resolved by dynamic code, not by a static declarative mapping.
Using subclasses and mapping them as "table per concrete class" might be of use. But it neither reduces your mapping effort, nor does it relieve you to use two objects for storing, as one object can't change the subclass it belongs to during runtime in Java. It will, however, relieve you from declaring the attributes twice in your POJOs. That's useful, as it relieves you, in your further development, to always keep the attribute lists of both classes in sync.
There might be an adventurous way to go. "Hibernate in Action", in section 3.3.4, shortly describes dynamic manipulation of mapping data, using PersistentClass. Browsing PersistentClass in the Javadoc didn't reveal to me a way to change the table the mapping refers to. The Hibernate manual doesn't even mention this mechanism. But I didn't search too thoroughly, so maybe this, or a related mechanism can be used for that.
The reason I didn't search too thoroughly is that I wouldn't bother using such a sophisticated and dangerous mechanism for such a simple function. The algorithm has to tell Hibernate somehow which table to write to, so why not take that subclass approach and express the location change by copying from one object to the other?
|