项目实体与员工实体的JPA映射

时间:2013-07-22 10:55:16

标签: hibernate jpa jpa-2.0

我想知道如何使用JPA

映射以下要求

我有一个项目实体,其中包含以下属性

projectNo (auto generated)
projectRequestedBy
approvedBy

员工实体

employeeNumber (primary key)
employeeName
employeeTitle
employeePhone

我想知道如何在Project Entity中有效地映射employeeNumber与projectRequestedBy和approvedBy属性?

我还想知道当我对employeeName实体类执行查询时,如何显示employeeTitleemployeePhoneProject属性?理想情况下,如果我尝试获取项目记录,我希望得到以下记录

projectNo projectRequestedByName projectRequestedByTitle  approvedByName approvedByTitle

任何帮助都非常值得赞赏。

更新1

项目实体

@Entity
@Table(name = "PROJECT")
public class Project

private Long projectNo;

@ManyToOne
@JoinColumn(name="EMP_NUMBER", insertable =false, updatable=false)
private Employees employees;

员工实体

@Entity
@Table(name = "EMPLOYEES")
public class Employees {
@OneToMany  
@JoinColumn(name="EMP_NUMBER", nullable = false)
private Collection<Project> project;

1 个答案:

答案 0 :(得分:1)

行。首先,您的映射是错误的。在双向OneToMany关联中,一方必须是反面,这由mappedBy属性实现。如图所示in the documentation

您实际上有两个员工和项目的OneToMany / ManyToOne。员工要求许多项目。一名员工批准了许多项目。

因此映射应该看起来像

@Entity
public class Employee
    @OneToMany(mappedBy = "requester")
    private Set<Project> requestedProjects;

    @OneToMany(mappedBy = "approver")
    private Set<Project> approvedProjects;
}

@Entity
public class Project
    @ManyToOne
    private Employee requester;

    @ManyToOne
    private Employee approver;
}

要在单个查询中获取带有请求者及其批准者的项目,

select p from Project p
left join fetch p.requester
left join fetch p.approver