创建子元素时的JPA Mapping异常

时间:2017-02-14 22:43:33

标签: java jpa one-to-many

我有那些持久化实体及其构造函数/ getter / setter:

@Entity
public class Budget {

    @Id
    @GeneratedValue
    private Long budgetId;

    private double totalAmount;

    private BudgetStatus status;

    private Instant created;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "budgetLineId")
    private List<BudgetLine> budgetLines = new ArrayList<>();

    // constructors / getters / setters

}

我想与这个实体建立一对多的单向关系:

@Entity
@Immutable
public class BudgetLine {

    @Id
    @GeneratedValue
    private Long budgetLineId;

    private String description;

    private int tooth;

    // constructors / getters / setters

}

我认为我已经正确地注释了实体,但我得到了这个例外:

  

无法添加或更新子行:外键约束失败   (&#39;牙医-app&#39;。&#39;预算线&#39;,CONSTRAINT&#39; FKn3er98a66as3vxuj1kij2q040&#39;   外键(&#39; budgetLineId&#39;)参考&#39;预算&#39; (&#39; budgetId&#39;))

使用此代码:

private List<Budget> createBudgets(Patient patient, BudgetStatus budgetStatus) {
    List<Budget> budgets = new ArrayList<Budget>();
    Treatment treatment = new Treatment("Implant");
    treatmentRepository.save(treatment);
    for (int i = 0; i < 5; i++) {
        List<BudgetLine> budgetLines = new ArrayList<>();
        BudgetLine budgetLine = budgetLineRepository.save(new BudgetLine("tooth", 120));
        budgetLines.add(budgetLine);
        Budget budget = budgetRepository
                .save(new Budget(10, 10, 300, "Comments", budgetStatus, patient, treatment, budgetLines));
        budgets.add(budget);
    }
    patient.setBudgets(budgets);
    patientRepository.save(patient);
    return budgets;
}

我不明白为什么在我持续BudgetLine个实例时遇到此异常,因为BudgetLine表不应该对{Budget表有任何外键限制1}}因为它是单向关系。关于什么事情的任何想法?感谢。

1 个答案:

答案 0 :(得分:1)

您的映射和表定义是错误的。 BudgetLine列是budgetId的唯一标识符,是自动生成的,不能是Budget budgetId列的连接列/外键}。您需要BudgetLine表中的其他@OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "budgetId") private List<BudgetLine> budgetLines = new ArrayList<>(); 列:

extension Float {
    func roundUpTo(multiplier: Int) -> Int{
        let fractionNum = self / Float(multiplier)
        return Int(ceil(fractionNum)) * multiplier
    }
}

另外,我不明白为什么你不会有外键约束,保证数据在数据库中的一致性,因为关联是单向的。您仍然需要外键约束来确保BudgetLine不指向未使用的预算。