我在我的项目中使用Hibernate / JPA 2.1进行持久化。我尝试保存一个FinancialInstrument,它有一个嵌入的字段interestRate,它有几个PlanStep。下面的映射是建立的:
@Entity
@Table(name = "tbl_financial_instrument")
public class FinancialInstrument {
@Embedded
private InterestRate interestRate;
// ...
}
@Embeddable
public class InterestRate {
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "ir_id")
private Set<InterestPaymentPlanStep> interestPaymentPlanSteps = new LinkedHashSet<>();
// ...
}计划步骤可以由不同的类重用,我在这里使用继承(单表类型)。
@Entity
@DiscriminatorValue("INTEREST_PAYMENT")
public class InterestPaymentPlanStep extends PlanStep {
// ...
}
@Entity
@Table(name = "tbl_plan_step")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "PLAN_STEP_TYPE", discriminatorType = DiscriminatorType.STRING)
public abstract class PlanStep extends AbstractBaseObject {
// ...
}我用一个包含计划步骤的InterestRate填充了一个金融工具。现在,我正在尝试将所有内容持久化到数据库中,我使用以下代码:
private void persistFinancialInstrument(FinancialInstrument financialInstrument) {
financialInstrument = financialInstrumentRepository.save(financialInstrument);
if (financialInstrument.getInterestRate() != null) {
Set<InterestPaymentPlanStep> interestRatePaymentPlanSteps = financialInstrument.getInterestRate().getInterestPaymentPlanSteps();
for (PlanStep planStep : interestRatePaymentPlanSteps) {
planStepRepository.save(planStep);
}
}
}现在奇怪的是,当我打开查询的日志记录时,我看到它执行了2个查询来持久化计划步骤:
这是第一个,请注意,它不包含金融工具的ID,而我已经在这里期望它:
insert into tbl_plan_step (creation_datetime, modification_datetime, amount, anchor_date, cap, cycle, floor, rate_add, rate_value, plan_step_type, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, 'INTEREST_PAYMENT', ?)第二个是:
update tbl_plan_step set ir_id=? where id=?我不知道为什么要在两个查询中执行保存。有人能为此找到一个解释吗?
发布于 2017-01-25 21:21:48
这可能是因为PlanStep与InterestRate没有关系。将链接设置为双向的。
@ManyToOne
private InterestRate interestRate在PlanStep中执行一次插入。
有关详细说明,请参阅hibernate documentation
https://stackoverflow.com/questions/41852381
复制相似问题