Hibernate Jpa Abstract: built-in identifier problem

I have this db schema:

TABLE_A [1] → [n] Table_C as well as TABLE_B [1] → [n] Table_C

Now PrimaryKey for Table_C is an EmbeddedId with a foreign key compared to Table_A and a foreign key compared to Table_B. How to mark this annotation?

My decision:

@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;
}
+5
source share
1 answer

When you follow the JPA specification, you will notice that there is no need to display table C. You can just use a compatible

Something like that

@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;
}

if you want to map something in JoinTable, you can also define it as Entity. You can map tablec like this

@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,...
}

/ , . id , pk.

+5

All Articles