Hibernate在表之间移动记录

时间:2013-05-23 05:59:28

标签: java hibernate

我需要处理批准记录并根据其状态使其成为可用的。我最初的想法是使用标志列来过滤记录,但严格隔离已批准/未批准记录的业务实践会阻止这种方法。对我来说,下一个最合理的方法是将记录移动到批准的表格中。

我使用entity-name属性将同一个类映射到两个不同的表 - APPROVED_和UNAPPROVED_。当我尝试移动记录时,它会从未批准的内容中删除,但不会插入已批准的内容。我打开了hibernate.show_sql并显示了检索/删除但没有插入。

已批准的表具有generator class =“assigned”,因此它使用未批准表中的id作为其键。

关于我做得不对的任何建议?或者更好的方法呢?

这是代码

    try {
        // begin transaction
        ses = Activator.getSession();
        ses.beginTransaction();
        dao.setSession(ses);
        daoMotor.setSession(ses);

        // for each input record in selectedMotors
        for (Long curId : selectedMotors) {
            // retrieve the input record
            IThreePhaseMotorInput record = dao.findById(curId, false);

            // save the motor into the permanent table using entity-name
            IThreePhaseMotor curMotor = record.getMotor();
            daoMotor.makePersistent("ThreePhaseMotor", (ThreePhaseMotor) curMotor);

            // delete the input record
            dao.makeTransient((ThreePhaseMotorInput) record);
        }

        // commit transaction
        ses.getTransaction().commit();
    } catch (Throwable t) {
        ErrorInfo info = ErrorInfoFactory.getUnknownDatabaseInfo(t, null, IThreePhaseMotorList.class.getName());
        Platform.getLog(Activator.getContext().getBundle()).log(
                new Status(IStatus.ERROR, Activator.PLUGIN_ID, info.getErrorDescription(), t));
        throw new BusinessException(info);
    } finally {
        if (ses != null && ses.isOpen()) {
            ses.close();
        }
    }

缩写为hbm.xml文件:

<class name="ThreePhaseMotorInput" table="THREE_PHASE_MOTOR_INPUT" lazy="false">
    <id name="id" type="java.lang.Long">
        <column name="ID" />
        <generator class="native" />
    </id>
    <version generated="never" name="version" type="java.lang.Integer" />
    <many-to-one name="motor" cascade="all" entity-name="UnapprovedThreePhaseMotor"  fetch="join">
        <column name="MOTOR" />
    </many-to-one>
</class>
<class name="ThreePhaseMotor" table="UNAPPROVED_THREE_PHASE_MOTOR" entity-name="UnapprovedThreePhaseMotor">
    <id name="id" type="java.lang.Long">
        <column name="ID" />
        <generator class="native" />
    </id>
    <version generated="never" name="version" type="java.lang.Integer" />
</class>
<class name="ThreePhaseMotor" table="THREE_PHASE_MOTOR"  entity-name="ApprovedThreePhaseMotor">
    <id name="id" type="java.lang.Long">
        <column name="ID" />
        <generator class="assigned" />
    </id>
    <version generated="never" name="version" type="java.lang.Integer" />

1 个答案:

答案 0 :(得分:1)

在睡觉之后(我的电线说我在睡觉时做了一些最好的思考!),我意识到问题就像gkamai建议的那样。我需要做一个深层复制。

更改

IThreePhaseMotor curMotor = record.getMotor();
daoMotor.makePersistent("ThreePhaseMotor", (ThreePhaseMotor) curMotor);

IThreePhaseMotor curMotor = new ThreePhaseMotor(record.getMotor());
daoMotor.makePersistent("ThreePhaseMotor", (ThreePhaseMotor) curMotor);