How to add a separate primary key to the connection table in sleep mode

I have a question about Hibernate ManyToMany mappings. I have two classes A and B, and the mapping between them is the ManyToMany mapping allowed by Hibernate:

@Entity @Table(name="A") public class A { @Id @GeneratedValue private Long id; @ManyToMany @JoinTable(name="C", joinColumns=@JoinColumn (name="a_id"), inverseJoinColumns=@JoinColumn (name="b_id")) private Set bs; } @Entity @Table(name="B") public class B { @Id @GeneratedValue private Long id; @ManyToMany(mappedBy="bs") private Set bs; } 

As you can see, the Join table that I use is C. The foreign keys to A and B are "a_id" and "b_id". I understand that Hibernate creates a compiled primary key with a_id and b_id for table C.

I do not want to have a C entity in my model. But instead of the compiled primary key in table C, I would like to have a generated identifier and a unique constraint for the a_id and b_id fields.

Can I tell Hibernate to use a separate primary key? Without adding entity C?

I would be grateful for any help.

Thank you so much!

+6
java orm hibernate jpa
source share
3 answers

You have to do iyt like this. But it can only be used for a list (and not for sets)

 @Entity @TableGenerator(name="ids_generator", table="IDS") public class Passport { ... @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name="PASSPORT_VISASTAMP") @CollectionId( columns = @Column(name="COLLECTION_ID"), type=@Type (type="long"), generator = "ids_generator" ) private Collection<Stamp> visaStamp = new ArrayList(); ... } 
+5
source share

I do not think that's possible. And I don't see a problem in defining a C object.

If you have additional information in the connection table, it will not be available to you, because your Set contains the target object - A or B

In addition, your Set will be better off using generics - i.e. Set<A> and Set<B> .

Btw, Hibernate cannot be alarmed by the fact that the table creates another object - using the current mapping can work (without taking into account the id column). When you said that “Hibernate creates,” I suggested that you generate your schema from your entity model. Now, it seems the opposite is true, so give it a try.

+1
source share

But instead of the compiled primary key in table C, I would like to have a generated identifier and a unique constraint for the a_id and b_id fields.

Typically, a JoinTable primary key consists of a combination of both foreign keys. At least that's what the JPA will generate. But if you are not using the JPA provider to generate the model, and if PK can be generated by the database (using the IDENTITY column, trigger, etc.), you should be able to use table C for your ManyToMany association (without having to enter an additional entity and convert relationship to two OneToMany ). Did you really try?

+1
source share

All Articles