john
john

Reputation: 707

How to find all by number that starts with Spring JPA?

MyStore class contains itemNbr Integer. I want to find all where itemNbr starts with xxxxxx

I'm using Spring Repository like this . This is what I tried

@Repository 
public interface TestRepository extends CrudRepository<MyStore, Long> {
    List<MyStore> findByItemNbrStartsWith(int itemNbr);
} 

But this throws an exception

java.lang.IllegalArgumentException: Parameter value [2%] did not match expected type [java.lang.Integer (n/a)]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    a

Upvotes: 1

Views: 2341

Answers (1)

Amit Phaltankar
Amit Phaltankar

Reputation: 3424

With default methods you can't.

However you can write your own @Query something like this, and then pass the itemNbr as a String.

@query("from MyStore where CAST(itemNbr as text) like CONCAT(:itemNbr, '%')")
List<MyStore> findByItemNbrStringStartsWith(String itemNbr);

Upvotes: 2

Related Questions