根据 FK 检索关系上的字段

Retrieving a field on a relation based on the FK

我正在迈出进入 jpa 的第一步(将整个数据库从 jdbc 移植到 jpa),我想知道如何实现以下目标: 我有两个 table,一个 Users table 和一个 ProfileImages table,ProfileImages table 包含到 user_id 的 FK,然后是另一个字段字节数组(保存图像的字节)。

我想要实现的是能够直接在我的用户模型中恢复字节数组,如下所示:

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_userid_seq")
    @SequenceGenerator(name = "users_userid_seq", sequenceName = "users_userid_seq", allocationSize = 1)
    private Long userId;

    @Column
    private String name;

    @Column
    private String surname;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false, unique = true)
    private String email;

    @Column
    private String password;

    @Column(nullable = false, unique = true)
    private Integer fileNumber;

    @Column
    private boolean isAdmin;

    // Map the byte array from the profile_image relation
    private byte[] image;

    .....
    .....
}

注意:最好不要更改架构以使用户持有字节数组。

您可以使用 SecondaryTable 注释将两个表映射到一个 Entity:

@Entity
@Table(name = "users")
@SecondaryTable(name = "profileimages",
                pkJoinColumns = @PrimaryKeyJoinColumn(name = "user_id"))
public class User {

    @Column(name = "image", table = "profileimages")
    private byte[] image;

另请查看文档: https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#sql-custom-crud-secondary-table-example