在Hibernate中映射两个相同的表(相同的模式...)到同一个实体 [英] Map Two Identical tables ( same schema...) to same entity in Hibernate
问题描述
我如何在XML映射的hibernate中实现这一点。
所以我的目标是当我在DAO中查询时,如果两个表映射到同一个实体,它如何知道从哪个表中拉取。
我试图不创建一个父类,然后再创建两个子类。
谢谢
很抱歉,迟到的答案。我在stackoverflow上多次回答了这个问题。
为了将两个相同的表映射到一个实体类中,您需要使用Hibernate或NHibernate的 entity-name
属性。
例如,要将单个类Order映射到Order和OrderHistory表,您可以使用新的实体名称
( Order
和 OrderHistory
)如下所示:
< hibernate-mapping xmlns =urn :NHibernate的映射-2.2\" >
< class name =DomainModel.Order,DomainModel
table =Ordersentity-name =Order>`
< id name =_ idaccess =字段column =OrderId>
< generator class =assigned/>
< / id>
< property name = ...>
< / class>
< class name =DomainModel.Order,DomainModel
table =OrderHistoriesentity-name =OrderHistory>
< id name =_ idaccess =fieldcolumn =OrderId>
< generator class =assigned/>
< / id>
< property name = ...>
< / class>
< / hibernate-mapping>
然后根据您需要的实体类型,只需调用相应的Session方法即可:
_session.Save(Order,myOrder)
或
_session.Save(OrderHistory,myOrder)
简单,是不是?
一般 entity-name
必须在所有Hibernate调用中替换类名称。
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.
I m trying to Not create a parent class and then two subclasses.
Thanks
Sorry for the late answer. i have answered this question several times on stackoverflow.
To map two identical tables onto one entity class, you need to use the entity-name
property of Hibernate or NHibernate.
Documentation is here: 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:
<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.Save("Order", myOrder)
or
_session.Save("OrderHistory", myOrder)
Simple, isn't ?
In general entity-name
must replace class name in all Hibernate calls.
这篇关于在Hibernate中映射两个相同的表(相同的模式...)到同一个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!