简体   繁体   中英

Hibernate : Map single VO to two tables

I have two tables - Table1 and Table2 . Data structure of both the tables is same. I have single VO for both Table1 and Table2 . I have two .hbm.xml file for two tables separately - Table1.hbm.xml and Table2.hbm.xml

In my java code, based on a condition I either need to save to Table1 or Table2

if(someCondition)
{
session.saveOrUpdate(VO); //This should be for Table1
}
else
{
session.saveOrUpdate(VO); //This should be for Table2
}

My problem is since that VO is same, there will be conflict in deciding which table to save.

Is it possible to have same VO mapped to two tables?

Note : The reason why I have such a requirement is Table1 and Table2 are in separate tablespace. One is partitioned and the other is not. There are couple of other reasons for such a weird requirement which is beyond my control to change the architecture now.

In my opinion using two entity managers is a bit too much. What you need is to have a good abstraction around the table.

You can map the same class as many times you want you just have to map it under different name.

Than one good Repository pattern working with the abstract entity (instead of the concrete one) combined with a Factory or Builder to generate the two objects will get the job done. If you follow this approach you will not need to have this IF-ELSE flow.

@MappedSuperClass
class AbstractMappedSomeTimes {
      private mappedAttribute;
}

@Table("yourtablename")
public class  MappedOnce extends AbstractEntity{

}

@Table("yourtablename")
public class  MappedTwise extends AbstractEntity{

}

Than you can have Repository working with AbstractMappedSomeTimes types of objects. You can also create a Factory that will generate either MappedOnce objects or MappedTwise objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM