How to create relationship to the same entity with JPA (Hibernate)?

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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).

How can I implement this?

I tried something standard

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

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

回答1:

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:

(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.



回答2:

This should work:

@OneToOne @JoinColumn(name="manager") private User manager;


回答3:

you should put the name of the column which you want to join to your User entity. The name can be anything you want, its how it will appear in your database. "manager_id" or whatever.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!