Tharindu Eranga
Tharindu Eranga

Reputation: 167

Spring Data JPA Method naming contains query for double value

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.

Upvotes: 0

Views: 3896

Answers (1)

V&#252;sal
V&#252;sal

Reputation: 2706

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.

Upvotes: 2

Related Questions