java 将两个相同的表(相同的架构...)映射到 Hibernate 中的相同实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4997950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map Two Identical tables ( same schema...) to same entity in Hibernate
提问by Sammy
I have table1 and table2 that have the same schema... and I want to have only one entity rather than two ( since the fields will be the same). How would I achieve that in hibernate with XML mapping. So my goal is when I m querying in the DAO, how would it know which table to pull from if both tables are mapped to the same entity.
我有 table1 和 table2 具有相同的模式......我只想有一个实体而不是两个(因为字段将相同)。我将如何使用 XML 映射在休眠中实现这一点。所以我的目标是当我在 DAO 中查询时,如果两个表都映射到同一个实体,它如何知道从哪个表中提取。
I m trying to Not create a parent class and then two subclasses.
我试图不创建一个父类,然后创建两个子类。
Thanks
谢谢
回答by Sisyphus
Sorry for the late answer. i have answered this question several times on stackoverflow.
抱歉回复晚了。我已经在 stackoverflow 上多次回答过这个问题。
To map two identical tables onto one entity class, you need to use the entity-name
property of Hibernate or NHibernate.
要将两个相同的表映射到一个实体类,您需要使用entity-name
Hibernate 或 NHibernate的属性。
Documentation is here: http://docs.jboss.org/hibernate/core/3.2/reference/en/html/mapping.html#mapping-entityname
文档在这里:http: //docs.jboss.org/hibernate/core/3.2/reference/en/html/mapping.html#mapping-entityname
For example, to map a single class Order to Order and OrderHistory tables, you create a mapping file that maps the order class to the two tables using new entity-names
(Order
and OrderHistory
) like this:
例如,要将单个类 Order 映射到 Order 和 OrderHistory 表,您可以创建一个映射文件,使用 new entity-names
(Order
和OrderHistory
)将订单类映射到两个表,如下所示:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="DomainModel.Order, DomainModel"
table="Orders" entity-name="Order">`
<id name="_id" access="field" column="OrderId">
<generator class="assigned"/>
</id>
<property name= ...>
</class>
<class name="DomainModel.Order, DomainModel"
table="OrderHistories" entity-name="OrderHistory">
<id name="_id" access="field" column="OrderId">
<generator class="assigned"/>
</id>
<property name= ...>
</class>
</hibernate-mapping>
Then depending on the type of entity you need, you simply call the appropriate Session methods as:
然后根据您需要的实体类型,您只需调用适当的 Session 方法:
_session.Save("Order", myOrder)
or
或者
_session.Save("OrderHistory", myOrder)
Simple, isn't ?
很简单,不是吗?
In general entity-name
must replace class name in all Hibernate calls.
通常entity-name
必须在所有 Hibernate 调用中替换类名。