2


我有 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 文件,其中映射了这些类。

我的测试代码片段:

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

PS我的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;
    }
}
4

2 回答 2

1

尝试在表属性中提供数据库名称,例如 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>  
于 2010-11-16T11:16:20.043 回答
0

该解决方案似乎有效的 链接文本

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.
于 2010-11-16T11:15:51.183 回答