将两个或多个hibernate hbm文件映射到单个java pojo类

时间:2017-05-22 05:43:52

标签: java spring hibernate hibernate-mapping hbm2java

表A的hbm.xml文件,其MyClass中的pojo类

<class name="com.entities.MyClass" table="A" entity-name="tableOne">
    <id name="id" access="field" type="java.lang.Long">
        <column name="ID" />
        <generator class="increment" />
    </id>
    <property name="columnOne" type="java.lang.String">
        <column name="COLUMN_ONE" />
    </property>
    <property name="columnTwo" type="java.lang.String">
        <column name="COLUMN_TWO" />
    </property>
</class>

表B的hbm.xml文件(它也有相同的pojo类“MyClass”)

<class name="com.entities.MyClass" table="B" entity-name="tableTwo">
    <id name="id" access="field" type="java.lang.Long">
        <column name="ID" />
        <generator class="increment" />
    </id>
    <property name="columnOne" type="java.lang.String">
        <column name="COLUMN_ONE" />
    </property>
    <property name="columnTwo" type="java.lang.String">
        <column name="COLUMN_TWO" />
    </property>
</class>

这是POJO类

package com.entities;

public class MyClass{

    Long id;
    String columnOne;
    String columnTwo;
    public MyClass() {
        // TODO Auto-generated constructor stub
    }
    public MyClass(Long id, String columnOne, String columnTwo) {
        super();
        this.id = id;
        this.columnOne = columnOne;
        this.columnTwo = columnTwo;
    }
    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }
    /**
     * @return the columnOne
     */
    public String getColumnOne() {
        return columnOne;
    }
    /**
     * @param columnOne the columnOne to set
     */
    public void setColumnOne(String columnOne) {
        this.columnOne = columnOne;
    }
    /**
     * @return the columnTwo
     */
    public String getColumnTwo() {
        return columnTwo;
    }
    /**
     * @param columnTwo the columnTwo to set
     */
    public void setColumnTwo(String columnTwo) {
        this.columnTwo = columnTwo;
    }
}

如何插入表格?我尝试了以下代码:

session.save("tableOne",myClassObj);
transaction.commit();

但在提交时会抛出以下异常

Hibernate: select max(ID) from A

org.hibernate.MappingException: Unknown entity: com.entities.MyClass

1 个答案:

答案 0 :(得分:0)

您可以按表格使用如下

session.save("A",myClassObj);
transaction.commit();