Reputation: 365
I am trying to learn Hibernate to create on startup the Db from entities, but I have only found articles suggesting how to implement many to many relationship with only 2 entities, but what if I wanted to have a lookup table with its own entity and add an int column
for example this created a many to many relationship with only 2 entities but can I have a 3rd entity that handles both entities relationship and add another column?
@Entity(name="Categories")
@Table(name="Categories")
public class Categories {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="CategoriesId")
public int Id;
@Column(name="Name",length = 255,nullable = false)
public String Name;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "Categories")
public List<Product> Products = new ArrayList<>(0);
}
@Entity(name = "Products")
@Table(name="Products")
public class Product {
@Id
@Column(name="ProductId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int Id;
@Column(name="Name",length = 255,nullable = false)
public String Name;
@Column(name="Price",nullable = true)
public double Price;
public com.RestApiTest.demo.Models.Entities.Categories getCategory(int index) {
return Categories.get(index);
}
public void setCategory(com.RestApiTest.demo.Models.Entities.Categories category,int index) {
Categories.set(index,category);
}
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "ProductCategories",
joinColumns = { @JoinColumn(name = "ProductId") },
inverseJoinColumns = { @JoinColumn(name = "CategoriesId") })
List<Categories> Categories = new ArrayList<>(0);
}
Upvotes: 0
Views: 173
Reputation: 310
You can do that by making an association Entity e.g ProductsCategories ,Product will have a @OneToMany relation to it and same with Categorie ,the ProductsCategories class will have an EmbeddedId composed of the primary keys of the Product and Category Entities ,that's basically the approach to it ,hope this helps !
Upvotes: 1