使用注释将一个实体映射到两个不同的表中

时间:2022-03-15 06:35:52

I have a lot of trouble with the following problem. I have an Entity "Home" which I use at two different locations within my code. The problem is, that it is necessary to map this entity to different tables depending on the class they were used in.

我遇到以下问题很麻烦。我有一个实体“Home”,我在我的代码中的两个不同位置使用它。问题是,有必要根据它们使用的类将该实体映射到不同的表。

If we assume I would have the two classes Class1 and Class2. Both classes have the an attribute of the "Home" type. Now I want that of attribute within class1 is mapped to the Table "CLASS1_HOME" and the attribute of class2 is mapped to the table "CLASS2_HOME".

如果我们假设我有两个类Class1和Class2。这两个类都具有“Home”类型的属性。现在我希望class1中的属性映射到表“CLASS1_HOME”,并且class2的属性映射到表“CLASS2_HOME”。

I know that this is possible by e.g., using "MappedSuperClass" for the class "Home" and create a further class "Second_Home" which inherits all attributes from class "home". But my Question is if there is a possibilty to this without inheritance, because the attributes of home will not change and I think the "inheritance" solution is a kind of "dirty". Moreover, I want to this only by using annotations.

我知道这可以通过例如使用“MappedSuperClass”用于类“Home”并创建另一个类“Second_Home”来继承类“home”的所有属性。但我的问题是如果没有继承就有可能,因为家的属性不会改变,我认为“继承”解决方案是一种“肮脏”。而且,我只想通过使用注释来实现这一点。

Is there a way to do it as I described it ?

有没有办法像我描述的那样去做?

1 个解决方案

#1


0  

If you don't want to use inheritance, and if you are saving HOME the same way in both CLASS1_HOME and CLASS2_HOME table, I do suggest something like this:

如果您不想使用继承,并且如果您在CLASS1_HOME和CLASS2_HOME表中以相同的方式保存HOME,我建议这样的事情:

public class Home{
boolean Class1;
}

in this case when you persist it you can simply figure out if this is for Class1 or not. And if you want, based on the flag persisted in your database, you can create two views of CLASS1_Home and CLASS2_Home

在这种情况下,当你坚持它时,你可以简单地判断这是否适用于Class1。如果您愿意,基于数据库中持久存在的标志,您可以创建CLASS1_Home和CLASS2_Home的两个视图

#1


0  

If you don't want to use inheritance, and if you are saving HOME the same way in both CLASS1_HOME and CLASS2_HOME table, I do suggest something like this:

如果您不想使用继承,并且如果您在CLASS1_HOME和CLASS2_HOME表中以相同的方式保存HOME,我建议这样的事情:

public class Home{
boolean Class1;
}

in this case when you persist it you can simply figure out if this is for Class1 or not. And if you want, based on the flag persisted in your database, you can create two views of CLASS1_Home and CLASS2_Home

在这种情况下,当你坚持它时,你可以简单地判断这是否适用于Class1。如果您愿意,基于数据库中持久存在的标志,您可以创建CLASS1_Home和CLASS2_Home的两个视图