映射具有两个的实体引用另一个相同的实体 [英] mapping a entity which have two refer to another same entity

查看:99
本文介绍了映射具有两个的实体引用另一个相同的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体,其中一个(任务)拥有另一个实体(用户)的两个参照.

I have two entity,one of them(the Task) own two refers of another entity(The user).

public class Task{
    private int id;

    private User publisher;

    private List<User> manager;
}

public User{
    private int id;
    private String name;
    private List<Task> tasks;
}

在任务端,我可以将一对一"设置为发布者",将一对多"设置为管理者",但是如何在用户端设置映射?

At the Task side,I can set "one-to-one" to "publisher",and "one-to-many" to "manager",but how to set the mapping in the user side?

推荐答案

这取决于您想要在数据库中拥有什么.

It depends on what you want to have in the database.

如果要为publisher使用单独的外键并为manager连接表,则最简单的映射方式是:

If you want to have a separate foreign key for publisher and join table for manager, the easiest way to map the other side it this:

public class Task{
    @ManyToOne 
    private User publisher;

    @ManyToMany
    private List<User> manager;

     ...
}

public User{
     @OneToMany(mappedBy = "publisher")
     private List<Task> publishedTasks;

     @ManyToMany(mappedBy = "manager")
     private List<Task> managedTasks;

     ...
}

如果您确实需要User中的单个任务列表,则可以以编程方式创建它.

If you actaully need a single list of tasks in User, you can create it programmatically.

或者,您可以具有一个带有附加Role属性的单个联接表:

Alternatively, you can have a single join table with an additional Role property:

public enum Role { PUBLISHER, MANAGER }

public class Task{
    @ManyToMany
    @MapKeyEnumerated
    private Map<Role, User> participants;
     ...
}

public User{
    @ManyToMany(mappedBy = "participants")
    private List<Task> tasks;
     ...
}

还要考虑是否需要这种关系是双向的.当您需要特定用户参与的所有任务的列表时,似乎没有太多用例.也许您根本不需要在User端建立这种关系,而可以使用查询代替.

Also think whether you need this relationship to be bidirectional at all. It looks like there are not so many use cases when you need a list of all tasks where a particular user participate. Perhaps you don't need this relationship at the User side at all, and can use queries instead.

这篇关于映射具有两个的实体引用另一个相同的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆