英文:
Spring JPA - CriteriaQuery for Composite key variables
问题
我的情景是,库存是根类,InventoryId 是如下所定义的复合键类:
@Entity
@Data
public class Inventory implements java.io.Serializable {
private static final long serialVersionUID = 748080717136028484L;
@Id
private InventoryId id;
}
@Data
@Embeddable
public class InventoryId implements java.io.Serializable {
private static final long serialVersionUID = 6479717401762529315L;
@Column(nullable = false, length = 50)
private String productId;
@Column(nullable = false, length = 50)
private String branchId;
}
使用如下的 Criteria 查询:
@Override
public List<Inventory> getInventoryLevelsPerProduct(String productId, String branchId) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Inventory> cq = cb.createQuery(Inventory.class);
Root<Inventory> root = cq.from(Inventory.class);
List<Predicate> predicates = new ArrayList<>();
InventoryId inventoryId = new InventoryId();
if (StringUtils.isNotEmpty(productId)) {
inventoryId.setProductId(productId);
predicates.add(cb.equal(root.get("id"), inventoryId));
}
if (StringUtils.isNotEmpty(branchId)) {
inventoryId.setBranchId(branchId);
predicates.add(cb.equal(root.get("id"), inventoryId));
}
cq.where(predicates.toArray(new Predicate[0]));
return entityManager.createQuery(cq).getResultList();
}
如果我传递 productId 和 branchId,它会返回记录。当我们传递一个输入搜索条件时,如何使此查询可行?
提前感谢您的帮助。
英文:
My scenario is, Inventory is root class and InventoryId is composite key class as defined below:
@Entity
@Data
public class Inventory implements java.io.Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 748080717136028484L;
/** The id. */
@Id
private InventoryId id;
}
@Data
@Embeddable
public class InventoryId implements java.io.Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 6479717401762529315L;
/** The product id. */
@Column(nullable = false, length = 50)
private String productId;
/** The branch id. */
@Column(nullable = false, length = 50)
private String branchId;
}
Using the Criteria query as below:
@Override
public List<Inventory> getInventoryLevelsPerProduct(String productId,String branchId) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Inventory> cq = cb.createQuery(Inventory.class);
Root<Inventory> root = cq.from(Inventory.class);
List<Predicate> predicates = new ArrayList<>();
InventoryId inventoryId = new InventoryId();
if (StringUtils.isNotEmpty(productId)) {
inventoryId.setProductId(productId);
predicates.add(cb.equal(root.get("id"), inventoryId ));
}
if (StringUtils.isNotEmpty(branchId)) {
inventoryId.setBranchId(branchId);
predicates.add(cb.equal(root.get("id"), inventoryId));
}
cq.where(predicates.toArray(new Predicate[0]));
return entityManager.createQuery(cq).getResultList();
}
If I pass productId and branchId it is returning the records. How to make this query workable when we pass one input search criteria?
Thanks in advance.
专注分享java语言的经验与见解,让所有开发者获益!
评论