Hibernate manytomany @JoinTable + @ Secondary repeated entries

I have a relationship like @ManyToMany with the association @JoinTable .

The fact is that an object in relation has its own table, but a couple of properties should go to the association table.

Table A_C is fine, I think.

Adding a duplicate of @SecondaryTable .

 @Entity @Table(name = "A") @SecondaryTable(name = "A_C", pkJoinColumns = { @PrimaryKeyJoinColumn(columnDefinition = "A_ID", name = "A_ID")}) class A { @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "A_B", joinColumns = {@JoinColumn(name = "A_ID")}, inverseJoinColumns = {@JoinColumn(name = "B_ID")}) private List<B> bs = new ArrayList<B>(); @Column(table = "A_B") private int b1; } @Entity @Table(name = "B") @SecondaryTable(name = "A_B", pkJoinColumns = { @PrimaryKeyJoinColumn(columnDefinition = "B_ID", name = "B_ID")}) class B { @Column(table = "A_B") private int a1; @Column(table = "A_B") private int a2; @ManyToMany(mappedBy = "A_ID", fetch = FetchType.LAZY) private List<A> as = new ArrayList<A>(); } 

This while maintaining A entities B duplicated in such a way, where:

 A_ID B_ID a1 a2 1 0 1 1 1 1 0 0 

Where should be

 A_ID B_ID a1 a2 1 1 1 1 

With @Embeddable will not work either.

ssedano.

+4
source share
1 answer

A_B is the join table for table A and B , but you also use it as an extra table for B

This does not work. What values ​​should B.a1 and B.a2 have if a B assigned to several A s?

There are three possibilities: * a1 and a2 belong to the association. In this case, you need an association class that stores this additional information. * a1 and a2 belong only to B: a1 and a2 should not be in table A_B * A is the composition of B : table A_B and B must be combined, and the many-to-many relationship is replaced by the one-to-many relationship.

Without specific names for attributes that are hard to say, they really belong.

0
source

Source: https://habr.com/ru/post/1414903/


All Articles