我有2个类:用户和消息。
一个用户可以拥有多条消息。
即这是一对多的关联。
我的users表位于第一个数据库中,而messages表位于第二个数据库中。
我该如何映射它们?
我的用户和消息表映射:
<hibernate-mapping>
<class name="com.example.hibernate.User" table="users" lazy="false">
<id name="xId" type="int" column="xid" >
<generator class="increment"/>
</id>
<set name="messages" inverse="true" table="messages">
<key>
<column name="xsin_id" not-null="true" />
</key>
<one-to-many class="com.example.hibernate.Message" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.example.hibernate.Message" table="messages" lazy="false">
<id name="id" type="int" column="xmsgbox" >
<generator class="increment"/>
</id>
<many-to-one name="user" class="com.example.hibernate.User">
<column name="xsin_id" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
我还有2 * .cfg.xml文件,其中映射了这些类。
我的测试代码snipplet:
Session session = HibernateUtilUser.getSession();
String SQL_QUERY ="from User user";
Query query = session.createQuery(SQL_QUERY);
User user = null;
for(Iterator it=query.iterate();it.hasNext();){
user=(User)it.next();
break;
}
Set<Message> messages = user.getMessages();
assertNotNull(messages);
我收到错误:关联引用未映射的类:com.example.hibernate.Message
P.S。我的HibernateUtilUser类:
public class HibernateUtilUser {
private static SessionFactory sf;
private static Session session;
private HibernateUtil() {}
public static SessionFactory getSessionFactory() {
if (sf == null) {
sf = new Configuration().configure("hibernateuser.cfg.xml").buildSessionFactory();
}
return sf;
}
public static Session getSession() {
if (session == null || session.isOpen() == false) {
session = getSessionFactory().openSession();
}
return session;
}
public Session openSession() {
return sf.openSession();
}
public static void close(){
if (sf != null)
sf.close();
sf = null;
}
}
答案 0 :(得分:1)
尝试在table属性中提供DB名称,例如table =“[your another DB Name] .. messages”
<set name="messages" inverse="true" table="AnotherDB..messages">
<key>
<column name="xsin_id" not-null="true" />
</key>
<one-to-many class="com.example.hibernate.Message" />
</set>
答案 1 :(得分:0)
此解决方案似乎有效 link text
You need to use one SessionFactory only. Then, in the mapping files for your classes, use the schema or catalog attributes. For example:
Code:
<class name="Test1" table="Test1" catalog="...">
<class name="Test2" table="Test2" catalog="...">
This of course assumes that the databases lives in the same MySQL server.