我在我的项目中使用 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 {
// ...
}
我已经用利率填写了金融工具,其中包含计划步骤。现在我尝试将所有内容保存到数据库中,我使用以下代码:
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=?
我不知道为什么要在 2 个查询中执行保存。谁能解释一下吗?
最佳答案
这可能是由于 PlanStep 与 InterestRate 没有关系。使链接双向。
@ManyToOne
private InterestRate interestRate
在 PlanStep 中执行单个插入。
参见hibernate documentation详细解释
关于java - 一对多引用使用继承映射映射的实体会导致插入,然后更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852381/