I am using the following mechanism as per the user guide. It works when the query returns a result but get an exception when there is no result returned.
totalHours = dataManager.loadValue(
"select sum(e.resourceHoursRequired) from erp$PlanOrderContinuousProd e " +
"where e.prodDate = :prodDate and e.operation.id = :opsId group by e.prodDate", BigDecimal.class)
.parameter("prodDate", planDate)
.parameter("opsId", operation.getId())
.one();
The exception is as follows:
java.lang.IllegalStateException: No results
at com.haulmont.cuba.core.global.FluentValueLoader.one(FluentValueLoader.java:112)
Is there any straightforward way we can get value 0 instead of this exception?
you can use optional() (see API docs), which will return you a java.util.Optional, which you can easily check for existence. With orElse() - API docs you can return the value or a default value.
Thanks Mario.
So, the code will look like as follows:
totalHours = dataManager.loadValue(
"select sum(e.resourceHoursRequired) from erp$PlanOrderContinuousProd e " +
"where e.prodDate = :prodDate and e.operation.id = :opsId group by e.prodDate", BigDecimal.class)
.parameter("prodDate", planDate)
.parameter("opsId", operation.getId())
.optional().orElse(BigDecimal.ZERO);
I have used following alternative codes:
Query query1 = em.createQuery("select COALESCE(sum(e.resourceHoursRequired),0) " +
"from erp$PlanOrderContinuousProd e " +
"where e.prodDate = :prodDate and e.operation.id = :opsId group by e.prodDate")
.setParameter("prodDate", planDate)
.setParameter("opsId", operation.getId());
If both are used in server side, is there any reason one should be picked as a preference between the above two when one using DataManager and other use em?
Thanks. I came across this comparison ealier but was interested in exchanging thoughts. can we say EntityManager will perform better when we do not need security restriction as DataManager checks by default?
Thanks Konstantin for the suggestion. So you mean even in server side, one should prefer use of DataManager when there is no transnational operation and persistence context used. I know you have a very deep knowledge of this technical aspects, will do so without any doubt. Just curious, if there is any reason of recommending use of DataManager as preferred one?