首页 > 解决方案 > 在休眠中一对一映射的父类中保存关系ID

问题描述

我有两个简单的类,称为 Student 和 Location

@Entity
public class Student {

    private String name;
    private Integer id;

    @OneToOne(fetch = FetchType.EAGER, mappedBy = "student", cascade = CascadeType.PERSIST)
    @JsonProperty("location")
    private Location location;


    /* Getters and Setters */

}

@Entity
public class Location {

    private Integer id;
    private String locationName;
    private String street;
    private String postalCode;

    @OneToOne(fetch = FetchType.EAGER)
    @PrimaryKeyJoinColumn
    @JoinColumn(name = "student_id")
    private Student student;


    /* Getters and Setters */

}

目前,该模式是这样的,即学生的id存储在位置表中,但在逻辑上Location独立于Student实体。它Student应该有Location实体的ID

根据我在网上看到的所有示例,在我的案例Location中,它的子类最终具有映射关系。我尝试通过在变量上设置属性来反转mappedby属性,private Student student;但它似乎没有在数据库中创建该列。

我在 REST 请求中得到的 JSON 的结构如下:

"students": [
        {
            "id": 1234,
            "name": "John Doe",
            "location": {
                "id": "5678", 
                "locationName": "St.Mary",
                "street": "Wellington St",
                "postalCode": "41298"
            }
        },
        .
        .
        .
        .
        /* Can have more students here */
    ]

所以数据库明智这就是我希望架构看起来像的样子:

students
id name location_id

locations
id location_name street postal_code

有人可以指出我正确的方向。我真的很感激这方面的一些帮助,因为我已经被这个问题困扰了一段时间

标签: hibernatejpaone-to-one

解决方案


Location是参考表。参考表应使用@ManyToOne注释进行映射。Location如果可以更简单地处理数据,则可以立即加载。但我更喜欢默认的惰性方法。也不@JoinColumn是必需的(默认情况下使用它)。但它使映射更清晰,可用于指定连接列名称。注释也@ForeignKey可用于指定外键约束名称。

@Entity
public class Student {

    @Id
    private Integer id;

    @Column 
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn
    private Location location;

}

@Entity
public class Location {

    @Id
    private Integer id;

    @Column
    private String locationName;

}

推荐阅读