我需要处理批准记录并根据其状态使它们可用。我最初的想法是使用标志列来过滤记录,但严格隔离已批准/未批准记录的业务实践阻止了这种方法。下一个最合乎逻辑的方法(对我来说)是将记录移动到批准的表中。
我正在使用实体名称属性将同一类映射到两个不同的表 - APPROVED_ 和 UNAPPROVED_。当我尝试移动记录时,它会从未批准的记录中删除但不会插入已批准的记录。我打开了 hibernate.show_sql 并且显示了检索/删除但没有插入。
已批准的表具有生成器类="已分配",因此它使用未批准表中的 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" />
最佳答案
睡在上面之后(我的电报说我在 sleep 时做了一些最好的思考!),我意识到问题正如 gkamai 所建议的那样。我需要做一个深拷贝。
改变
IThreePhaseMotor curMotor = record.getMotor();
daoMotor.makePersistent("ThreePhaseMotor", (ThreePhaseMotor) curMotor);
到
IThreePhaseMotor curMotor = new ThreePhaseMotor(record.getMotor());
daoMotor.makePersistent("ThreePhaseMotor", (ThreePhaseMotor) curMotor);
关于java - Hibernate 在表之间移动记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16706570/