【问题标题】:Many to One Relation on same table同一张表上的多对一关系
【发布时间】:2017-04-21 23:39:24
【问题描述】:

您认为是一家公司。该公司在用户表上有员工。经理必须在用户表上。

例子:

Users Table : John Watson userID=1 managerId=2(manager id have userID value)
              Emilia Clarke userID=2 managerID=null(Because this user is a Manager)

你觉得我是怎么做到的? managerID 行与用户表的多对一关系(尽管有同一张表)

John Watson 的 Emilia Clark 经理(因为 john 的 managerID,emilia 的用户 ID

【问题讨论】:

  • 为了提高您的问题的质量,请包括一个示例数据表(带有记录)和另一个显示所需输出的表。请参考您进行的研究,特别提到任何特别有用的研究。请向我们展示您尝试过的代码(如果有)以及代码产生的任何错误消息的全文。有关如何提问的更多信息,请阅读stackoverflow.com/help/how-to-ask

标签: mysql sql hibernate jpa


【解决方案1】:

只需留下 userId 并添加一个布尔值 isManager,如果用户是经理,则其值为 true,否则为 false。

【讨论】:

  • 对不起,我没有告诉你。我指的是 John Watson 的 Emilia Clark 经理(因为 john 的 managerID,emilia 的用户 ID
【解决方案2】:

要获取员工列表及其经理的详细信息,请尝试以下操作...

SELECT employee.userID,
       employee.userName,
       manager.userID,
       manager.userName
FROM Users AS employee
JOIN Users AS manager ON employee.managerID = manager.userID
ORDER BY employee.userName,
         employee.userID;

要获取经理及其员工的列表,请尝试以下操作...

SELECT manager.userID,
       manager.userName
       employee.userID,
       employee.userName,
FROM Users AS manager
JOIN Users AS employee ON manager.userID = employee.managerID
ORDER BY manager.userName,
         manager.userID,
         employee.userName,
         employee.userID;

(后面的解释……)

如果您有任何问题或cmets,请随时发表评论。

【讨论】:

    【解决方案3】:

    您可以如下映射:

    @Entity
    @Table(name = "users")
    public class User {
    
        @Id
        @Column(name = "user_id")
        @GeneratedValue(strategy = ...)
        private Long id;
    
        @OneToMany(mappedBy = "manager")
        private Set<User> employees;
    
        @ManyToOne
        @JoinColumn(name = "manager_id"
        private User manager;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2013-02-17
      • 2012-08-27
      • 2020-09-09
      • 1970-01-01
      • 2015-11-12
      • 2014-07-11
      相关资源
      最近更新 更多