简体   繁体   English

休眠:将单个VO映射到两个表

[英]Hibernate : Map single VO to two tables

I have two tables - Table1 and Table2 . 我有两个表Table1Table2 Data structure of both the tables is same. 两个表的数据结构相同。 I have single VO for both Table1 and Table2 . 我对Table1Table2都有一个VO。 I have two .hbm.xml file for two tables separately - Table1.hbm.xml and Table2.hbm.xml 我分别为两个表有两个.hbm.xml文件Table1.hbm.xmlTable2.hbm.xml

In my java code, based on a condition I either need to save to Table1 or Table2 在我的Java代码中,根据条件,我需要保存到Table1Table2

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. 我的问题是,由于VO相同,因此在决定保存哪个表时会发生冲突。

Is it possible to have same VO mapped to two tables? 是否可以将相同的VO映射到两个表?

Note : The reason why I have such a requirement is Table1 and Table2 are in separate tablespace. 注意 :之所以有这样的要求,是因为Table1和Table2位于单独的表空间中。 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. 与将抽象实体(而不是具体实体)一起使用Factory或Builder来生成两个对象的一种良好的Repository模式相比,它将完成工作。 If you follow this approach you will not need to have this IF-ELSE flow. 如果您采用这种方法,则不需要此IF-ELSE流程。

@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. 比起使用Repository可以处理AbstractMappedSomeTimes类型的对象而言。 You can also create a Factory that will generate either MappedOnce objects or MappedTwise objects. 您还可以创建一个Factory,该工厂将生成MappedOnce对象或MappedTwise对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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