我在使用JPA批注时遇到问题。 我创建了3个表: -类别 -类别_产品 -产品
我为类别,产品和数据透视表创建了3个不同的实体:
@Entity
@Table(name="categories")
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="category_id")
@JsonBackReference
private Category parentCategory;
@OneToMany(mappedBy="parentCategory", fetch = FetchType.EAGER)
@JsonManagedReference
private List<Category> childCategory;
public Category() {
}
// Getters and setters
}
我的产品实体:
@Entity
@Table(name="products")
@NamedQuery(name="Product.findAll", query="SELECT p FROM Product p")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
@Lob
private String description;
private int instock;
private BigDecimal unitprice;
private int createdat;
private int updatedat;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "product_id")
private List<Image> images;
public Product() {}
// getters and setters
}
还有我的数据透视表:
@Entity
@Table(name="categories_products")
@NamedQuery(name="CategoriesProduct.findAll", query="SELECT c FROM CategoriesProduct c")
public class CategoriesProduct implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column(name="category_id")
private int categoryId;
@Column(name="product_id")
private int productId;
// Getters and setters
}
实际上,我需要查看某个类别的产品和该产品的类别,我被困住了,因为似乎我们无法两次获得渴望的产品。对于类别,我已经有一个用于获取子类别的oneToMany,对于产品而言,已经具有用于获取产品照片的oneToMany