java - hibernate spring jpa中的双向一对一

标签 java spring-mvc spring-boot spring-data-jpa

class Transaction implements Serializable {

    @OneToOne(mappedBy = "transaction")
    @JoinColumn(name = "invoice_id", nullable = false)
    private InvoiceDetails invoice;

    // some other columns, getter and setter
}

class InvoiceDetails implements Serializable {

    @OneToOne(mappedBy = "invoice", fetch = FetchType.LAZY)
    @JoinColumn(name = "transaction")
    private Transaction transaction;

    // some other column and getter setter
}

编译时出现错误 - 未知的mappedBy:com.project.model.Transaction.invoice,引用的属性未知:com.project.model.InvoiceDetails.transaction

但是,当我从 InvoiceDetails 中删除 mappedBy = "invoice" 时,它会进行编译。但是,交易表中有引用 InvoiceDetails 的列。 InvoiceDetails 中有一个列存储来自 Transaction 的 Id。

我还没有尝试获取数据。我现在只看到数据库中的列。

最佳答案

当您在 JPA 中具有双向关系时,您应该仅在其中一个属性中设置 mappedBy。没有 mappedBy 的列将具有其表中的关系具有外键约束的列,而另一个则不会具有该关系的任何列。因为 mappedBy 表示此关系由您在关系的另一端指定的属性处理。

关于java - hibernate spring jpa中的双向一对一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401621/

相关文章:

java - 将元素追加到 List<String, String>

java - 如何使用mapstruct映射到List<>

java - PassiveExpiringMap 不会使对象过期

java - Spring @Value 注释总是评估为空?

java - Spring - 找不到 key 'could not find key ' logging.exception-conversion-word'

java - Android webview,检测网站是否请求位置权限

formatting - 如何在 Spring MVC 3.0 中显示格式化的 DateTime?

Spring 实体应该在服务中转换为 Dto 吗?

java - 考虑重新访问上面的条目或在您的配置中定义类型为 'org.springframework.data.redis.core.RedisTemplate' 的 bean

java - Spring Boot事务管理器建议回滚所有异常