按编号搜索从 spring 数据 jpa 开始
Search by number starts with in spring data jpa
我正在使用 Spring 数据 jpa,MySQL。
我有以下实体
User {
BigDecimal userNo;
String name;
}
Mysqltable貌似,
user(userNo decimal(10, 0), name text);
我想搜索 userNo
以 开头的所有 users
,例如 12。
我怎样才能在 spring 数据 jpa 中做到这一点。
我试过使用,
userDao.findByUserNoStartingWith(BigDecimal userNo);
但它不起作用并抛出异常
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [12%] did not match expected type [java.math.BigDecimal (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [12%] did not match expected type [java.math.BigDecimal (n/a)]
如何使用派生查询或 jpa 查询进行搜索?
我认为您最好的选择是编写一个执行类似
的查询
select *
from user
where cast(userNo as char) like 12%
由于Spring数据本身无法生成这样的查询,您必须自己指定。由于 cast
不是 JPQL,您还必须告诉 Spring 数据它是本机 SQL 查询。
public interface UserDao extends JpaRepository<User, BigDecimal> {
@Query(value = "select u from user u where cast(userNo as char) like :userNo%",
native = true)
public List<User> find(@Param("userNo") String userNo);
}
我正在使用 Spring 数据 jpa,MySQL。 我有以下实体
User {
BigDecimal userNo;
String name;
}
Mysqltable貌似,
user(userNo decimal(10, 0), name text);
我想搜索 userNo
以 开头的所有 users
,例如 12。
我怎样才能在 spring 数据 jpa 中做到这一点。
我试过使用,
userDao.findByUserNoStartingWith(BigDecimal userNo);
但它不起作用并抛出异常
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [12%] did not match expected type [java.math.BigDecimal (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [12%] did not match expected type [java.math.BigDecimal (n/a)]
如何使用派生查询或 jpa 查询进行搜索?
我认为您最好的选择是编写一个执行类似
的查询select *
from user
where cast(userNo as char) like 12%
由于Spring数据本身无法生成这样的查询,您必须自己指定。由于 cast
不是 JPQL,您还必须告诉 Spring 数据它是本机 SQL 查询。
public interface UserDao extends JpaRepository<User, BigDecimal> {
@Query(value = "select u from user u where cast(userNo as char) like :userNo%",
native = true)
public List<User> find(@Param("userNo") String userNo);
}