I have the following situation:
I am trying to create an application that is multi-tenant with the same tenants in the same database with the same tables. As you know, Hibernate does not support this option until 5.0, as I found.
I am trying to solve this by adding a brandId field to each table.
As I create a many-to-many relationship, I also added this brand identifier to the Join ManyToMany table here (I donβt know if I can do this, mysql does not complain). I made a foreign key for both tables, while both include brand
So now I have a Text table (ID, name, brandId) and a tag (ID, name, brandId) and a connection table (text_id, tag_id, brand_id), where the foreign keys
CONSTRAINT FK_TAG_TEXTS_TAG FOREIGN KEY (TAG_ID,BRAND_ID) REFERENCES TAG (ID,brand), CONSTRAINT FK_TAG_TEXTS_TEXT FOREIGN KEY (TEXT_ID,BRAND_ID) REFERENCES TEXT (ID,brand)
As you can see, the brand ID is used twice.
Then I generated my classes using the Hibernate Tools, which created the composite primary key class as it should, and the association in the tag class.
@ManyToMany(fetch = FetchType.EAGER,cascade = {CascadeType.PERSIST,CascadeType.MERGE }) @JoinTable(name = "tag_texts", , joinColumns = { @JoinColumn(name = "TAG_ID", nullable = false, insertable = false, updatable = false), @JoinColumn(name = "BRAND_ID", nullable = false, insertable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "TEXT_ID", insertable = false, nullable = false, updatable = false),@JoinColumn( name = "BRAND_ID", insertable = false, nullable = false, updatable = false) }) public List<Text> getTexts() { return this.texts; }
The problem is that I get the following exception:
org.hibernate.MappingException: repeat column in collection mapping: de.company.domain.Tag.texts column: brand_id
I looked at the Hibernate code in the Collection class, which throws an exception. Here, the checkColumnDupliation method is called, which uses Set and inserts the name, which means that inserting "BRAND_ID" as the column a second time leads to this behavior.
As I found, the most common solution for a column repeat error is to insert "insertable = false and updateable = false" when using the same column in multiple links. This is described here:
Sleep mode: where insertable = false, updatable = false refer to composite groupings of primary keys with foreign keys?
But this does not seem to be the same problem as mine.
So my question is: is there any way to fix this with JPA Annotations and use the brand ID in both joinColumns and inverseJoinColumns?