Hibernate Jpa注释:嵌入式ID的问题

时间:2011-07-06 10:32:04

标签: hibernate jpa annotations

我有这个db模式:

表-A [1] - > [n]的Table_C 和 表-B [1] - > [n]的Table_C

现在,Table_C的PrimaryKey是一个EmbeddedId,其外键与Table_A和外键与Table_B相对。我如何记下这个注释?

我的解决方案是:

@Entity
public class TableA{
    @Id @column(name="ID")
    public int id;

    @OneToMany(mappedBy="tableA")
    public List<TableC> listOftableC; 
}

@Entity
public class TableB{
    @Id @column(name="ID")
    public String id;

    @OneToMany(mappedBy="tableB")
    public List<TableC> listOftableC; 

}

@Entity
public class TableC{
    @EmbeddedId
    public TableCPK idComposite;
}

@Embeddable
public class TableCPK{

    @ManyToOne
    @JoinColumn(name = "ID_TABLE_A", referencedColumnName="ID")
    public TableA tableA;

    @ManyToOne
    @JoinColumn(name = "ID_TABLE_B", referencedColumnName="ID")
    public TableA tableB;
}

1 个答案:

答案 0 :(得分:5)

当您遵循JPA规范时,您会注意到不需要映射tableC。你可以使用连接表

像这样的东西

@Entity
public class TableA{
    @Id
    @column(name="ID")
    public int id;
    @ManyToMany
    @JoinTable(name="TableC",
            joinColumns = {@JoinColumn(name = "ID_TABLE_A", referencedColumnName="ID")},
            inverseJoinColumns = {@JoinColumn(name = "ID_TABLE_B", referencedColumnName="ID")
    })
    public List<TableB> listOftableB;
}
@Entity 
public class TableB{
     @Id @column(name="ID")
     public String id;
     @OneToMany(mappedBy="listOftableB")
     public List<TableA> listOftableA;
}

如果要在JoinTable中映射某些内容,您还可以将其定义为实体。你可以像这样映射tableC

@Entity
public class TableC{
    @EmbeddedId
    private MyId id;
    @ManyToOne
    @JoinColumn(name = "ID_TABLE_A", insertable = false, updatable = false)
    private TableB tableA;
    @ManyToOne
    @JoinColumn(name = "ID_TABLE_B", insertable = false, updatable = false)
    private TableB tableB;

    @Column(name="extra_field")
    private String extraField;
}

@Embeddable
public class MyId{
    @Column(name="ID_TABLE_A")
    private int idTableA;
    @Column(name="ID_TABLE_B")
    private int idTableB;
    // equals, hascode,...
}

通过使对象可插入/可更新为false,您可以多次映射相同的属性。 id中的其他属性是offcourse不可更新的,因为你会破坏你的pk。