0

i have an entity which contains some attributes and i want to write a like (contains) query for all of its attributes with one single parameter from front controller. i have successfully achieved it for the String values but for the numeric (long, double) values, i cannot use containing keyword as it throws an exception (Parameter value ['%10%'] did not match expected type java.lang.Double()... something...).

my entity fields

    private String firstName;
    private double rating;

my repository query method

    List<MobileUser> findByFirstNameIgnoreCaseContainingOrRatingContaining(String value, double value2);

my service layer method which takes only one value

public List<MobileUserDTO> getMobileUsersLike(String value) {
    // parses the value and if it is not a numeric value it will be -1 (this is also a bad logic)
    Double parseDouble = (double) -1;
    try { parseDouble = Double.parseDouble(value); } catch (NumberFormatException ignored) { }
    // calls repository
    List<MobileUser> allUsersLike = mobileUserRepository.findByFirstNameIgnoreCaseContainingOrRatingContaining(value, parseDouble);
    return getMobileUserDtoList(allUsersLike);
}

how do i achieve this? thank you.

Tharindu Eranga
  • 137
  • 3
  • 12
  • Are you using plain SQL or JPQL as the query language? – sanemain Oct 29 '19 at 17:15
  • 1
    Probably you should use CriteriaBuilder, check this other issue out: https://stackoverflow.com/questions/43603951/jpa-criteriabuilder-like-on-double/43604207 and if you haven't used CriteriaBuilder before, than check this out :) -> https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/ – Kinga l Oct 29 '19 at 18:24
  • How can you use SQL's `like` expression for `Double`? Could you please describe your problem in detail so we can propose a better solution? – Vüsal Oct 29 '19 at 19:44
  • @sanemain JPQL query method. no Query annotation. only method name. – Tharindu Eranga Oct 30 '19 at 03:34
  • @Vusal i can use like query for double via a native query. it works also for int and long in mysql. but i need this in spring data jpa. – Tharindu Eranga Oct 30 '19 at 03:36

1 Answers1

2

You can try to use JPQL query:

@Query("FROM MobileUser WHERE firstName like %:firstName% OR CAST(rating AS TEXT) LIKE %:rating% ")
List<MobileUser> findByNameAndRating(@Param("name") String firstName, @Param("rating") String rating);

You can't use SQL like for double unless you cast it to String.

Vüsal
  • 2,580
  • 1
  • 12
  • 31