Spring JPA - 连接非持久性字段



我正在使用带有JPA的Spring Boot Web来开发活动规划应用程序。目前,我正在开发一个公共用户配置文件功能,我需要帮助来设计它,因为我不确定加入非持久字段的最佳方式。

用户类:

@Entity
@Table(name = "users")
public class User extends BaseEntity {
    @Column(name = "name")
    private String name;
    @Column(name = "email", unique = true)
    private String email;
    @Column(name = "profile_picture")
    private String profilePicture;
    @Column(name = "facebook_token")
    private String facebookToken;
    other fields, method, and private data...
}

类:

public class UserProfile {
    private final String name;
    private final String email;
    private final String profilePicture;
    ...
}

来宾类:

@Entity
@Table(name = "guests")
public class Guest extends BaseEntity {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "event_id")
    private Event event;
    @Column(name = "status")
    private String status;
    @Column(name = "is_attending")
    private boolean isAttending;
}

考虑到UserProfileUser类的减少,并且它是非持久性的,将UserProfile类保持在Guest类中的最佳方法是什么?

您可以使用嵌入式类将UserProfile保存在Guest类中,但它将是抗拒的。如果您希望 UserProfile 的所有属性都是非持久性的,则必须向其的每个属性添加@Transient

不能在 JPA 中将非实体作为关系,因为 JPA 不知道 UserProfile。

一种解决方案是将用户配置文件作为用户的基类,然后使用@Inheritence mapp 用户配置文件和用户。

然后,您可以在来宾和用户配置文件之间建立持久的关系

我不明白为什么你需要诚实地这样做。无论如何,您只需执行以下操作,但这是一种不好的做法,因为您将DTO放在实体中,而不是相反:

@Transient UserProfile userProfile;

为什么不懒洋洋地将访客与用户加入?或者使用来宾和用户从用户配置文件继承,如其他人所述。

另一种选择是简单地使用户配置文件成为只读视图,仅从用户获取所需的列。

最新更新