如何使用JPA(Hibernate)创建与同一个实体的关系? [英] How to create relationship to the same entity with JPA (Hibernate)?

查看:110
本文介绍了如何使用JPA(Hibernate)创建与同一个实体的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体 User ,它应该有属性 manager ,其中manager是另一个用户(一位经理可以管理许多用户,任何用户可能只有1个经理或没有任何)。

I have an entity User and it should have property manager where manager is another user (one manager can manage many users, any user may have only 1 manager or have not any).

我怎么能实现这个?

我尝试了一些标准

@ManyToOne
@JoinColumn (name = ??? /* what should be here? */, nullable = true)
private User manager;

但它并不像看起来那么简单..

but it's not as simple as it seems..

推荐答案

有什么问题?如果您不知道如何命名连接列(应该默认为MANAGER_ID),请使用默认值,即不要设置名称。从 <$ c的javadoc

What's the problem? Use the default value i.e. don't set the name if you don't know how to name the join column (should default to something like MANAGER_ID). From the javadoc of the name attribute:


(可选)外键的名称关键
。找到
的表取决于上下文。 如果连接
用于OneToOne或Many-ToOne
映射,则外键列位于
源实体的表中
。如果
连接用于ManyToMany,则外部
键位于连接表中。缺省值(如果使用单个连接列为
,则只应用
):
的连接:引用
关系属性的名称或
的字段参考实体; _;
的名称是引用的主键列。如果

实体中不存在这样的引用
关系属性或字段,那么连接列名由
组成,如下所示:
该实体; _;所引用的主键列的名称

(Optional) The name of the foreign key column. The table in which it is found depends upon the context. If the join is for a OneToOne or Many- ToOne mapping, the foreign key column is in the table of the source entity. If the join is for a ManyToMany, the foreign key is in a join table. Default (only applies if a single join column is used): The concatenation of the following: the name of the referencing relationship property or field of the referencing entity; "_"; the name of the referenced primary key column. If there is no such referencing relationship property or field in the entity, the join column name is formed as the concatenation of the following: the name of the entity; "_"; the name of the referenced primary key column.

这篇关于如何使用JPA(Hibernate)创建与同一个实体的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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