您好,请问使用EntityManager创建Query进行查询。Query是否有与数据加载器类似的removeParameter的方法,方便将输入为空的parameter直接remove掉。
try (Transaction tx = persistence.createTransaction()) {
// get EntityManager for the current transaction
EntityManager em = persistence.getEntityManager();
// create and execute Query
Query query = em.createQuery(
"select sum(o.amount) from sample$Order o where o.customer.id = :customerId");
query.setParameter("customerId", customerId);
result = (BigDecimal) query.getFirstResult();
// commit transaction
tx.commit();
}
如上,JPQL 语句里已经包含了参数,不能再remove 掉。可以考虑在拼接查询语句的时候处理。
最近正好写了个类似的:
query = entityManager.createQuery("select o from app_table1" +
+ " o where 1=1"
+ (noDate ? "" : " and o.createTs < :createDate")
+ (noLocation ? "" : " and o.location in :locations")
+ " order by o.createTs");
if (!noDate) {
query = query.setParameter("createDate", createDate);
}
if (!noLocation) {
query = query.setParameter("locations", locationList);
}
List values = query.getResultList();
1 个赞
在网上也找到了另一种方式,如下
List list = dataManager.loadValues(“select e.faultReasonName as name,count(e.faultReason) as amount from serviceproject_EventFullProperty e where e.deviceType=:deviceType and (e.eventDate=:startDate or :startDate is null) and (e.eventDate=:endDate or :endDate is null) group by e.faultReason”)
.properties(“name”,“amount”).parameter(“deviceType”,deviceTypeId).parameter(“startDate”,startDate.getValue()).parameter(“endDate”,endDate.getValue()).list();
这里是用datamanager实现的,使用entity manager应该也是一样的
2 个赞