CriteriaBuilder IN - java

An error occurred while executing this code:
public Iterable<T> findAllByIds(List<Integer> ids) {
Path<Integer> idField = root.get("id");
Predicate in = idField.in(ids);
query.select(root);
query.where(in);
query.orderBy(builder.asc(idField));
List<T> result = entityManager.createQuery(query).getResultList();
return result;
}
In line 2 the following exception is thrown:
Caused by: java.lang.IllegalArgumentException: Unaware how to convert value [[100, 101] : java.util.Arrays$ArrayList] to requested type [java.lang.Integer]
Hibernate version 5.2.11.Final, Java 8.

Try this :-
public Iterable<T> findAllByIds(List<Integer> ids) {
Expression<Integer> exp = root.get("id");
Predicate in = exp.in(ids);
query.select(root);
query.where(in);
query.orderBy(builder.asc(root.get("id")));
List<T> result = entityManager.createQuery(query).getResultList();
return result;
}

Related

Combining JPA And/Or Criteria Predicates

I want to query like: (sku = 'A' AND uom_code = 'B') OR (sku =
C' AND uom_code = 'D')
But my predicate generate such as (sku = 'A' AND uom_code = 'B' OR sku = 'C' AND uom_code = 'D')
how to fix it. Thank you.
public class VariantSpecification implements Specification<VariantModel> {
private final VariantFilter filter;
public VariantSpecification(VariantFilter filter) {
this.filter = filter;
}
#Override
public Predicate toPredicate(
Root<VariantModel> root,
CriteriaQuery<?> query,
CriteriaBuilder cb
) {
final List<Predicate> predicates = new ArrayList<>();
if (filter.getMerchantId() != null) {
predicates.add(cb.equal(root.get("merchantId"), filter.getMerchantId()));
}
Predicate predicate = cb.and(predicates.toArray(new Predicate[0]));
List<Predicate> predicatesMap = new ArrayList<>();
if (!CollectionUtils.isEmpty(filter.getSkusUoms())) {
filter.getSkusUoms().forEach(pair -> {
String sku = pair.getLeft();
String uom = pair.getRight();
Predicate predicateSku = cb.equal(root.get("sku"), sku);
Predicate predicateUom = cb.equal(root.get("uomCode"), uom);
predicatesMap.add(cb.or(cb.and(predicateSku, predicateUom)));
});
}
if (!predicatesMap.isEmpty()) {
Predicate predicateSector = cb.or(predicatesMap.toArray(new Predicate[0]));
return cb.and(predicate, predicateSector);
}
return predicate;
}
}
Yeah my mistake,
SELECT ... FROM ... WHERE (expression1 AND expression2) OR (expression3 AND expression4)
SELECT ... FROM ... WHERE expression1 AND expression2 OR expression3 AND expression4
According to the SQL specification, both statements mean the same thing. It doesn't matter whether the statement contains the () or not, so Hibernate doesn't use them. The order of precedence is like this, similar to 1+2*3 is the same as 1+(2*3).

Hibernate QueryException Not all named parameters have been set:

When my query is executed i receive stack
Caused by: org.hibernate.QueryException: Not all named parameters have been set: [param0] [select count(generatedAlias0.id)
from Position as generatedAlias0 where generatedAlias0.rank=:param0]
Method where is executed
public Long CountPosition(Rank aRank, List<Long> Status, List<Long> aStatusInternal) {
QueryBuilder<PozycjaWRankingu> aQuery = queryCountLarge();
aQuery.whereEquals("rank", aRank);
aQuery.whereInNotEmpty("status", Status);
aQuery.whereInNotEmptyAndNotEquals("internal.state", aStatusInternal);
return aQuery.countLarge();
}
And finally Query Builder
public static <T> QueryBuilder<T> createCountLarge(EntityManager aEntityManager, Class<T> aClass) {
QueryBuilder r = new QueryBuilder();
r.em = aEntityManager;
r.criteriaBuilder = r.em.getCriteriaBuilder();
r.criteria = ret.criteriaBuilder.createQuery(Long.class);
r.root = ret.criteria.from(aClass);
r.criteria.select(ret.criteriaBuilder.count(ret.root.get("id")));
return r;
}
Any idea where is might be a problem ?
Edit
queryCountLarge() returns
QueryBuilder.createCountLarge(em, myClass);

CriteriaBuilder search in 2 table get performance issue

I try to search a list keyword on 2 different table by CriteriaBuilder and get performance issue on line 26.
Can someone help me to improve this.
public static Specification<TrainingBatchVolunteerDetails> filterVolunteers(final TrainingVolunteerForm form) {
return new Specification<TrainingBatchVolunteerDetails>() {
#Override
public Predicate toPredicate(Root<TrainingBatchVolunteerDetails> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
....
List<Predicate> predicates = new ArrayList<Predicate>();
Join<TrainingBatchVolunteerDetails, TrainingBatches> batches = root.join("batches");
Join<TrainingBatches, Training> training = batches.join("training");
training.join("trainingVolunteerDetails").join("eventBaseProfile");
Join<TrainingBatches, EventBaseProfile> eventBaseProfile = root.join("eventBaseProfile");
Join<EventBaseProfile, BaseProfile> baseProfile = eventBaseProfile.join("baseProfile");
Join<CtExtendProfile, BaseProfile> ctExtendProfile = null;
if (StringUtils.isNotEmpty(form.getNricName())) {
...
ctExtendProfile = baseProfile.join("ctExtendProfile", JoinType.LEFT);
List<String> keywords = new ArrayList<String>();
...
predicates.add(cb.or(
baseProfile.<String>get("identifierId").in(keywords),
ctExtendProfile.<String>get("birthCertificate").in(keywords)
));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}

CMIS session.queryObjects doesn't return aspects

I have a couple test functions I've written to illustrate a problem (or at least some behavior that I don't understand). I am just doing some basic CMIS queries on an Alfresco 4.2.e community repository, but am getting some unexpected results depending on whether I use session.query() or session.queryObjects(). Specifically, the queryObjects doesn't return properties for custom aspects. Both return the relationships/associations fine. Am I doing something wrong, or is this a bug? I'm using opencmis 0.10, and the CMIS 1.1 URL.
private static Collection<Document> testCmisObjectQuery(Session session) {
List<Document> rv = new LinkedList<>();
OperationContext opCon = session.createOperationContext();
opCon.setLoadSecondaryTypeProperties(true);
opCon.setIncludeRelationships(IncludeRelationships.BOTH);
ItemIterable<CmisObject> cmisObjs =
session.queryObjects("D:af:insuringFormInstance", null, false, opCon);
for (CmisObject o : cmisObjs) {
Document d = (Document) o;
rv.add(d);
printDocProps(d);
}
return rv;
}
private static Collection<Document> testCmisQuery(Session session) {
List<Document> rv = new LinkedList<>();
String queryString = "SELECT cmis:objectId FROM af:insuringFormInstance";
OperationContext opCon = session.createOperationContext();
opCon.setIncludeRelationships(IncludeRelationships.SOURCE);
ItemIterable<QueryResult> results = session.query(queryString, false);
for (QueryResult qResult : results) {
String objectId = qResult.getPropertyValueByQueryName("cmis:objectId");
Document doc = (Document) session.getObject(session.createObjectId(objectId),opCon);
printDocProps(doc);
rv.add(doc);
}
return rv;
}
Looks like, you are missing a join as in
select d.*, o.* from cmis:document as d join cm:ownable as o on d.cmis:objectId = o.cmis:objectId
Have a look at https://wiki.alfresco.com/wiki/CMIS#Aspect_Query for further details.

JPA & PostgreSQL: How do I call a stored procedure using NamedNativeQuery Annotation

Using Postgresql 8.1, Spring 3.0, Hibernate 3.6.
I have a method that calls a stored procedure that works without using Annotations, essentially it is
....
return (Integer) getJpaTemplate().execute(new JpaCallback() {
public Object doInJpa(EntityManager em) {
// Query query = em.createNamedQuery("checkZone");
Query query = em.createNativeQuery("select zoneArea from zoneArea(:pId, :zId)");
query.setParameter("pId", p.getId());
query.setParameter("zId", z.getId());
try {
return query.getSingleResult(); // Integer expected
} catch (NoResultException e) {
return 0;
}
}
});
....
How can I do this with Annotations, here's my attempt that does not work.
#NamedNativeQueries({
#NamedNativeQuery(
name = "checkZone",
query = "select zoneArea from zoneArea(:pId, :zId)",
hints = {
#QueryHint(name = "org.hibernate.callable", value = "true")
},
resultSetMapping = "scalar",
resultClass = Integer.class)})
#SqlResultSetMapping(name="scalar",columns=#ColumnResult(name="result"))
#Entity
and here is the Exception
Caused by: org.postgresql.util.PSQLException: This statement does not declare an OUT parameter. Use { ?= call ... } to declare one.
at org.postgresql.jdbc2.AbstractJdbc2Statement.registerOutParameter(AbstractJdbc2Statement.java:1849)
at org.postgresql.jdbc3.AbstractJdbc3Statement.registerOutParameter(AbstractJdbc3Statement.java:1513)
at org.hibernate.dialect.PostgreSQLDialect.registerResultSetOutParameter(PostgreSQLDialect.java:335)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1713)
at org.hibernate.loader.Loader.doQuery(Loader.java:801)
I have working code but would like to get this working with Annotations, any ideas appreciated.

Categories