hibernate - 在 JPA 中同时映射键和对象

我正在查看其他人的代码,但我从未见过为一对一映射映射的键和对象,这样做可以吗?

@Entity
@Table(name = "PROJECT_POINTER")
public class ProjectPointerEntity {

    private static Logger LOG = LoggerFactory.getLogger(ProjectPointerEntity.class);

    @Id
    @SequenceGenerator(name = "seqGen", sequenceName = "PROJECT_POINTER_SEQ", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqGen")
    @Column(name = "PROJECT_POINTER_ID")
    private Long projectPointerId;


    @Column(name = "HOSTING_LOCATION_KEY")
    private String hostingLocationKey;


    @OneToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "HOSTING_LOCATION_KEY", insertable = false, updatable = false)
    private HostingLocationEntity hostingLocation = new HostingLocationEntity();


    public String getHostingLocationKey() {
        return hostingLocationKey;
    }

    public void setHostingLocationKey(String hostingLocationKey) {
        this.hostingLocationKey = hostingLocationKey;
    }

    public HostingLocationEntity getHostingLocation() {
        return hostingLocation;
    }

    public void setHostingLocation(HostingLocationEntity hostingLocation) {
        this.hostingLocation = hostingLocation;
    }

}

最佳答案

这是允许的,既有好处也有后果。您会注意到,在第二个映射中,OneToOne 有一个 JoinColumn 注释,将字段标记为 insertable = false, updatable = false - 这实际上使 OneToOne 映射成为只读的。因此,要更改字段/关系,需要使用要引用的 HostingLocationEntity 实例中的 ID 值来设置 hostingLocationKey。 OneToOne 映射仍应更新,以保持对象模型与数据库同步。缺点是,除了维护这两个属性外,必须预先设置要使用的 ID 值——如果 HostingLocationEntity 是新的,JPA 不会为其分配 ID,然后自动更新外键字段,因为外键映射不可更新/可插入。

其中一个好处是有一个直接指向 HOSTING_LOCATION_KEY 外键的属性,允许应用程序直接在查询中使用它,而不是通过在查询中使用“projectPointerEntity.hostingLocation.id”来冒表连接的风险,或者必须获取 hostingLocation 以获取 id。最后一个好处被标记为 Eager 的映射所抵消,这意味着它总是被获取。因此,除非您的应用程序在 JPA 提供程序强制表连接的查询中使用 hostingLocationKey,否则它可能是多余的,因为应用程序无论如何都可以从引用的 hostingLocation 访问它。

https://stackoverflow.com/questions/24391074/

相关文章:

vim - 防止重复的 UltiSnips 匹配

git - 从 git 中的分支中提取最新提交

spring - 错误 : "Connection refused: connect. 验证连接属性

sorting - thenComparing 与 thenComparingInt 的性能 - 使

oracle - Mysql Workbench 将 sql 导出到 Oracle 11

ruby-on-rails - 不知道如何构建任务 - cucumber

c# - 在 Entity Framework 中删除聚合根的子对象

design-patterns - 策略接口(interface)中的策略模式和方法数量

stm32 - 如何使用带 PLL 的 HSE 将 RTC 时钟与 STM32 一起使用

json - 在 JSON-RPC 连接上读取多个 JSON 对象