I understand hibernate @JoinTable annotation, but I don't understand the inverseJoinColumns. What is it used for?
e.g.
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "stock_category", catalog = "mkyongdb", joinColumns = {
@JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID",
nullable = false, updatable = false) })
public Set<Category> getCategories() {
return this.categories;
}
The element 'joinColumns' is used to specify foreign key column of the join table which references the source table (the owner of the association). The element 'inverseJoinColumns' is used to specify foreign key column of the join table which references the target table (the inverse side of the association).
The @JoinTable annotation indicates that we will interact with the intermediary table (user_roles) and further you can see settings of the relationship including mapping of columns. The joinColumns attribute is responsible for the columns mapping of the owning side.
The @JoinTable annotation is used to specify the table name via the name attribute, as well as the Foreign Key column that references the post table (e.g., joinColumns ) and the Foreign Key column in the post_tag link table that references the Tag entity via the inverseJoinColumns attribute.
Quoting API on referencedColumnName: The name of the column referenced by this foreign key column. Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.
From the javadocs, it means:
(Optional) The foreign key columns of the join table which reference the primary table of the entity that does not own the association
In layman's terms, it is the column of Category
that will be used as a part of the JoinTable
relationship between the current entity and Category
.
If you don't specify joinColumns
and inverseJoinColumns
on the @JoinTable
annotation, the persistence provider assumes a primary key to primary key join relationship and still store the equivalent ID columns for two related entities in the table by default.
For example, we have 2 models: User and Role. The relationship between those 2 models will be Many-to-Many. User Model:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
Role Model:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
@Column(length = 20)
private ERole name;
The joinColumn attribute will connect to the owner side of the relationship, and the inverseJoinColumn to the other side
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With