Answer the question
In order to leave comments, you need to log in
How to link two relationships correctly in java?
I have three tables that have a ManyToMany relationship:
1. product
2. category
3. product_category (intermediate table)
@Entity
@Table(name = "category")
@Data
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@ManyToMany(mappedBy = "category")
private List<Product> productList;
}
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private String category;
private int price;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "product_categories",
joinColumns = @JoinColumn(name = "product_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categoryList;
}
create table prouct_categories(
product_id BIGINT REFERENCES product(id),
category_id BIGINT REFERENCES category(id)
);
Answer the question
In order to leave comments, you need to log in
I will answer based on your second question , to which I already wrote an answer:
@Entity
@Table(name = "category")
@Data
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Column(length = 1000)
private String description;
@ManyToMany(mappedBy = "categoryList")
private List<Product> productList;
}
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(length = 1000)
private String description;
private double price;
@ManyToMany(fetch = FetchType.LAZY, cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "product_categories",
joinColumns = @JoinColumn(name = "product_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categoryList;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question