【问题标题】:Retrieving a field on a relation based on the FK基于 FK 检索关系上的字段
【发布时间】:2021-12-03 23:33:43
【问题描述】:

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

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

@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;

    .....
    .....
}

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

【问题讨论】:

    标签: database hibernate spring-mvc jpa


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2019-09-26
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多