简体   繁体   中英

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

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

This should work:

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

What's the problem? Use the default value ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM