use like for integer value in namedquery Eclipselink

1.1k views Asked by At

when use namedQuery in entity class get error

  @NamedQuery(name = "Classification.search", query = "SELECT c FROM Classification c WHERE c.id LIKE  :value")

Method for call namedQuery

public List<Classification> search(String value) {
    Query query = getEntityManager().createNamedQuery("Classification.search", Classification.getClass()).setParameter("value", "%"+value+"%");
    query.setMaxResults(10);
    return query.getResultList();
}

java.lang.IllegalArgumentException: You have attempted to set a value of type class java.lang.String for parameter value with expected type of class java.lang.Integer from query string SELECT c FROM Classification c WHERE c.id LIKE :value.

but when use this method is work without Error.

public List<Classification> findLimited(String _clasif, int maxResult) {
    String querySt = "SELECT c FROM Classification c WHERE c.id LIKE '%" + _clasif + "%'";
    Query query = em.createQuery(querySt);
    query.setMaxResults(maxResult);
    List<Classification> classif;
    classif = query.getResultList();
    if (classif != null) {
        return classif;
    }
    return new ArrayList<>();
}

i use eclipselink 2.6 with JPA

2

There are 2 answers

1
Jeus On BEST ANSWER

i solve that by this code.

public List<Classification> search(String value) {
    Query query = getEntityManager().createQuery(getNamedQueryCode(entityClass, "Classification.search").replace(":value", value));
    query.setMaxResults(10);
    return query.getResultList();
}

this method get namedQuery string from entity class by nameKey and class.

private String getNamedQueryCode(Class<? extends Object> clazz, String namedQueryKey) {
    NamedQueries namedQueriesAnnotation = clazz.getAnnotation(NamedQueries.class);
    NamedQuery[] namedQueryAnnotations = namedQueriesAnnotation.value();

    String code = null;
    for (NamedQuery namedQuery : namedQueryAnnotations) {
        if (namedQuery.name().equals(namedQueryKey)) {
            code = namedQuery.query();
            break;
        }
    }

    if (code == null) {
        if (clazz.getSuperclass().getAnnotation(MappedSuperclass.class) != null) {
            code = getNamedQueryCode(clazz.getSuperclass(), namedQueryKey);
        }
    }

    //if not found
    return code;
}
2
Neil Stockton On

As per the BNF for JPQL, "LIKE" is for use with String values only. Use with non-String values would only be a vendor extension, and hence vendor-dependent. Whether it is part of a named query or criteria or string-based JPQL is irrelevant.

like_expression ::= string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]