我有一个hibernate映射,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.lwl.anlei.bl.model.imp">
<class name="PersonFo">
<id name="id" type="integer"/>
<property name="name" type="string"/>
<property name="info" type="string"/>
</class>
<sql-query name="person1">
<return alias="gb" class="PersonFo"/>
SELECT id as {gb.id},
name as {gb.name},
info as {gb.info}
FROM table
WHERE field1 = :param
</sql-query>
<sql-query name="person2">
<return alias="gb" class="PersonFo"/>
SELECT id as {gb.id},
second_name as {gb.name},
whatever as {gb.info}
FROM table
WHERE field2 = :param
</sql-query>
</hibernate-mapping>
这是我所拥有的简单知识。 在Java中,我以这种方式获取我的数据,使用“getQueryName”:
List<Person> myPersons =
session.getNamedQuery("person1").setString("param", "important text").list();
现在我必须使用视图而不是这些查询。我知道,我可以简单地将“SELECT xxx FROM view_person1”和“SELECT xxx FROM view_person2”写入sql-querys,但我更喜欢使用这样的东西:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.lwl.anlei.bl.model.imp">
<class name="PersonFo"
table="view_person1"
entity-name="view_person1" >
<id name="id" column="id" type="integer"/>
<property name="name" column="name" type="string"/>
<property name="info" column="info" type="string"/>
</class>
<class name="PersonFo"
table="view_person2"
entity-name="view_person2" >
<id name="id" column="id" type="integer"/>
<property name="name" column="name" type="string"/>
<property name="info" column="info" type="string"/>
</class>
</hibernate-mapping>
在另一个例子中,我看到了如何通过这种方式通过hibernate保存数据。 Map Two Identical tables ( same schema...) to same entity in Hibernate
他们只是使用:
_session.Save("view_person1", xxxx)
_session.Save("view_person2", xxxx)
但是,我如何查询数据?是否有类似的东西:
List<Person> myPersons =
session.getNamedEntity("view_person2").list();
帮助将非常受欢迎! 谢谢!
答案 0 :(得分:1)
使用polymorphism="explicit"
区分您的命名实体:
<class name="PersonFo"
table="view_person1"
entity-name="view_person1" polymorphism="explicit" >
<id name="id" column="id" type="integer"/>
<property name="name" column="name" type="string"/>
<property name="info" column="info" type="string"/>
</class>
<class name="PersonFo"
table="view_person2"
entity-name="view_person2" >
<id name="id" column="id" type="integer"/>
<property name="name" column="name" type="string"/>
<property name="info" column="info" type="string"/>
</class>
并查询您的命名实体,如下所示:
List list1 = session.createQuery("from view_person1").list();
List list2 = session.createQuery("from view_person2").list();