jpa映射两个属性

时间:2013-03-22 11:36:23

标签: java jpa one-to-many many-to-one

我需要具有CompanyUser.companyRolCompanyUsers关系的OneToMany属性,并在每个查询中完成。

JPA company_usr实体:

@Entity
@Table(name = "company_usr")
public class CompanyUser extends BaseModel implements Serializable {

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(nullable = false)
    private Company company;
    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "usr_id", nullable = false)
    private User user;

    @Column(nullable = false)
    private Boolean external;

    @OneToMany(fetch = FetchType.EAGER)
    private List<CompanyRolCompanyUser> companyRolCompanyUsers;

....

JPA companyRol_companyUsr entity:

@Entity
@Table(name = "companyRol_companyUsr")
public class CompanyRolCompanyUser extends BaseModel implements Serializable {

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumns({
        @JoinColumn(name="companyuser_company_id",    referencedColumnName="company_id"),
        @JoinColumn(name="companyuser_usr_id", referencedColumnName="usr_id")
        })
    private CompanyUser companyUser;

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    private CompanyRol companyRol;

....

如何正确设置mappedBy属性中的companyRolCompanyUsers

2 个答案:

答案 0 :(得分:0)

如果我得到你想要达到的目标,我认为你需要这样的东西:

@OneToMany(fetch = FetchType.EAGER, mappedBy="companyUser")
private List<CompanyRolCompanyUser> companyRolCompanyUsers;

答案 1 :(得分:0)

您可以为同一列创建两个属性,如下所示:

@JoinColumn(name = "CGRADO_CODIGO", referencedColumnName = "CGRADO_CODIGO")
    @ManyToOne
    @NotFound(action=NotFoundAction.IGNORE)
    private SipreGrado                  sipreGrado;

    @Column(name = "CGRADO_CODIGO",insertable=false,updatable=false)
    private String                      sipreGradoCodigo;

请记住,如果您有时将实体设为NULL,则可以使用该注释跳过它

@NotFound(action=NotFoundAction.IGNORE)

另外,请记住设置

insertable=false,updatable=false 

表示您不希望包含在插入/更新查询中的那个。