简体   繁体   中英

How to map a one-to-many result to a Hibernate entity which is joined using a non-primary key?

Suppose there are two classes, Manager and Engineer. Conceptually, an engineer can belong to only one manager and a manager can have multiple engineers but schematically they can be linked by the department id. However, there are no foreign key association between the classes.

public class Manager {
   .....
   private Long deptId; 
 } 

public class Engineer {
   .....
   private Long deptId; 
 }

The following query works in mySQL:

select * from manager m left join engineer e on m.dept_id = e.dept_id.

It returns multiple rows corresponding to the different employees sharing the same department as the manager. I'm not able to map the result of this query to the entities. I would like to do something like the following:

public class Manager {
   .....
   private Long deptId; 

   @OnetoMany
   private List<Engineer> engineers;
 } 

@ManytoOne and @OnetoMany annotations expect a foreign key to use for mapping so the above isn't working. Are there other ways to achieve this?

You need to specify @JoinColumn manually. Check out this article for details

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