我正在设置Spring-Data-JPA项目以从具有客户和产品映射以及当前状态的联接表中获取产品列表。如何在不创建实体的情况下使用JPA Criteria API来获取提供的customerId的产品列表为客户?
我读到可以通过在where子句中提供customerId来使用@NamedQuery来获取产品列表。我已经为Customer和Product创建了复合键结构,作为CustomerProductId(@Embeddable),具有customerId和productId映射以及实体CustomerProduct(@Entity )以保存表格数据。
我有一个联接表customer_product
,其中包含customer_id
,product_id
,created_on
和current_status
列的映射。
id INT(11) NOT NULL
customer_id INT(11) NOT NULL
product_id INT(11) NOT NULL
created_on DATETIME(6) NOT NULL
current_status ENUM('CART','WISHLIST','ORDERED')
我想从此联接表中使用JPA Criteria API来获取给定customerId的产品列表,而无需创建Customer
实体。
product
表结构:
id INT(11) NOT NULL
created_on DATETIME(6) NOT NULL
NAME VARCHAR(50) NOT NULL
description VARCHAR(1000) NULL
product_seller
表结构:
id INT(11) NOT NULL
product_id INT(11) NOT NULL
seller_id INT(11) NOT NULL
created_on DATETIME(6) NOT NULL
availability BOOLEAN
产品类包含一组卖方,这些卖方也使用额外的联接表product_seller
@Entity
@Table(name="product")
public class Product implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@NotBlank
private String name;
@OneToMany(cascade = CascadeType.REMOVE)
@JoinTable(name = "product_seller", joinColumns =
@JoinColumn(referencedColumnName = "product_id"),inverseJoinColumns =
@JoinColumn(referencedColumnName = "seller_id"))
private Set<Seller> sellers;
//Setters and getters
}
@Embeddable
public class CustomerProductId implements Serializable{
@Column(name="customer_id")
private Long customerId;
@Column(name="product_id")
private Long productId;
//equals and hashcode method
//Setters and getters
}
@Entity
@Table(name="customer_product")
public class CustomerProduct{
@EmbeddedId
private CustomerProductId customerProductId;
@ManyToOne
@MapsId("customerId")
@Column(name="customer_id")
private Long customerId;
@ManyToOne
@MapsId("productId")
private Product product;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdOn;
//Setters and getters
}
如何遵循用于获取给定customerId的产品列表的JPA标准API实现?
@Autowired
private EntityManager entityManager;
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
Root<CustomerProduct> customerProductRoot = criteriaQuery.from(CustomerProduct.class);
criteriaQuery.where(criteriaBuilder.equal(customerProductRoot.get("customerId"),customerId));
Join<CustomerProduct, Product> product= customerProductRoot.join("product");
CriteriaQuery<Product> selectCriteriaQuery = criteriaQuery.select(product);
TypedQuery<Product> query = entityManager.createQuery(selectCriteriaQuery);
return query.getResultList();