java - 我如何映射到具有同一实体的两个字段的对象?

标签 java spring hibernate jpa

在我的 Spring MVC 应用程序中,我有以下 User 实体(为简洁起见,已删除):

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String email;
    private String password;
}

以及以下Application实体:

@Entity
public class Application {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String type;
    private String summary;
}

我想扩展 Application 实体,使其具有 User 类型的提交者(申请人)和批准者(申请被分配给谁进行批准):

@Entity
public class Application {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String type;
    private String summary;

    private User submitter;
    private User approver;
}

以及对应的扩展User实体:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String email;
    private String password;

    private Set<Application> applications;
}

Application 可以有一个提交者和一个批准者,但是 User 可以有多个申请提交或等待他们的批准,所以我猜这是一个 @OneToMany 用户端的关系。

这意味着 Application 端的映射看起来像这样:

@Entity
public class Application {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String type;
    private String summary;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User submitter;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User approver;
}

但是我在关系的 User 端使用什么映射? 我想应该是这样的:

@OneToMany(mappedBy = {"approver", "submitter"})
private Set<Application> applications;

但据我所知,使用 mappedBy 引用多个列是不可能的。

我什至不确定我的方法是否正确。也许我应该在应用程序的 User 实体中有两个单独的字段?

我非常感谢有关如何执行此操作的任何建议。

最佳答案

对于您当前的映射,您只有一个从应用程序到用户的引用,即“user_id”。这意味着,当前提交者和批准者始终相同,我认为这不是您想要的。

在应用程序实体映射到的表上,您需要两个不同的列。它们需要不同的名称,并且应该像这样映射:

@ManyToOne
@JoinColumn(name = "user_id_submitter")
private User submitter;

@ManyToOne
@JoinColumn(name = "user_id_approver")
private User approver;

然后在您的用户实体上,您可以映射两个不同的@OneToMany 关系,例如像这样:

@OneToMany(mappedBy = "approver")
private Set<Application> applicationsApproved;

@OneToMany(mappedBy = "submitter")
private Set<Application> applicationsSubmitted;

如果您需要组合列表,请随意提供一种组合两个列表的方法:

public Set<Application> getApplications() {
    Set<Application> allApplications = new HashSet<>();
    allApplications.addAll(applicationsSubmitted);
    allApplications.addAll(applicationsApproved);
    return allApplications;
}

(请注意:合并后的List当然只能只读,不能写入和更新数据库,因为是组合)

关于java - 我如何映射到具有同一实体的两个字段的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50856115/

相关文章:

java - Netbeans 无法打开项目或任何东西

java - hibernate 。如何正确组织带有注释的一对多关系?

java - 使用 Jmeter 对登录功能进行一些测试后,在范围内找不到 bean userList

Java - 合并排序数组

java - 我的fragmentClass在medod onContextItemSelected中从ViewPager获取错误的页面

java - getHibernateTemplate.save() - 如何获得受影响的行/新的自动增量

Spring 5 Reactor - 每 1 秒发射一次元素

Java -Spring Boot - OAuth 2.0配置实现Google账户登录

java - 具有多个参数的方法的 Autowiring spring 注释

hibernate - 是否可以使用 Hibernate 中的条件选择列中具有最大值的数据?