Hibernate: how to map one-to-many with another database?
My users and messages tables mapping:
<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>
I also have 2 *.cfg.xml files where these classes are mapped.
My test code 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);
I get an error: Association references unmapped class: com.example.hibernate.Message
P.S. my HibernateUtilUser class:
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;
}
}
Try giving DB name in table proeprty, like 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>
This solution seems working 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.
精彩评论