JPA实体关系映射

OneToOne

 

public classEmployee implements Serializable {



         ……



    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)



    @JoinColumn(name = "ADDR_ID")



  private Address address;



… …



}

 

 

ManyToOne

 

public classEmployee implements Serializable {



         ……



    @ManyToOne(fetch = FetchType.LAZY)



    @JoinTable(name = "EMP_JOB", joinColumns = @JoinColumn(name = "EMP_ID"), inverseJoinColumns = @JoinColumn(name = "TITLE_ID"))



    //連接表 joinColumns參考主表的主鍵的列,inverseJoinColumns參考字段或屬性生成的表格的主鍵的列



  private JobTitle jobTitle;





    @ManyToOne(fetch = FetchType.LAZY)



    @JoinColumn(name = "MANAGER_ID")



  private Employee manager;



… …



}

 

 

OneToMany

 

public classEmployee implements Serializable {



         ……



    @OneToMany(mappedBy = "manager") //manager字段擁有關係



    private List<Employee> managedEmployees = newArrayList<Employee>();





    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true)



  private List<PhoneNumber> phoneNumbers = newArrayList<PhoneNumber>();





    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)



    @JoinColumn(name="EMP_ID")



    private List<Degree> degrees = newArrayList<Degree>();



         ……



}

 

 

ManyToMany

public classEmployee implements Serializable {



         ……



    @ManyToMany



    //連接表



    @JoinTable(name = "PROJ_EMP", joinColumns = @JoinColumn(name = "EMP_ID"), inverseJoinColumns = @JoinColumn(name = "PROJ_ID"))



   private List<Project> projects = newArrayList<Project>();



… …



}


 

 

联合主键映射

ManyToOne OneToMany ManyToMany映射,而且采用JoinTable映射,会出现联合主键,即双主键。

你可能感兴趣的:(jpa)