引用使用继承映射映射的实体的一对多导致插入,然后更新查询

时间:2017-01-25 13:05:01

标签: java hibernate jpa

我在我的项目中使用Hibernate / JPA 2.1来持久化。我尝试保存FinancialInstrument,其中包含嵌入字段interestRate,其中包含多个PlanStep s已设置以下映射:

@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=?

我不知道为什么在2个查询中执行保存。谁能找到解释呢?

1 个答案:

答案 0 :(得分:1)

这可能是由于PlanStep与InterestRate没有关系。使链接双向。

@ManyToOne
private InterestRate interestRate
在PlanStep中

执行单个插入。

请参阅hibernate documentation了解详情