我正在使用Spring API和连接到MySQL数据库的JPA构建一个带有REST API的应用程序。要在User类中搜索名称,我实现了一种查询方法:List< User > findByFirstnameLike( String name );
此方法仅返回完全匹配的结果,这不是我想要的。我误解了它的用法吗?
存储库界面:
public interface UserRepository extends JpaRepository<User, Long> {
public List< User > findByFirstname( String name );
public List< User > findByFirstnameLike( String name );
}
服务bean方法:
@Override
public List<User> findByFirstNameLike(String name) {
logger.info( "searching for first name: {}", name);
List< User > ret = userRepo.findByFirstnameLike(name);
if( null == ret ){
logger.info("No list returned from search");
}
else{
logger.info( "List size = {}", ret.size() );
}
return( ret );
}
REST接口方法:
@RequestMapping(
value="/{firstName}",
method=RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity< List< User > > SearchForUserByFirstName( @PathVariable( "firstName" ) String firstName ){
return( new ResponseEntity< List< User > >( userService.findByFirstNameLike( firstName ), HttpStatus.OK) );
}
实体类:
@Entity
public class User {
public enum Department {
BS, BA, BT, BD, UX, SALES
}
@Id
@GeneratedValue
private Long id;
private String firstname;
private String lastname;
private String email;
private String phone;
private Department department;
所以......在数据库中有一个名为“Adam”的用户,查询方法返回除“Adam”之外的任何字符串的空列表。
编辑2: 在打开show SQL并将对象插入数据库之后,我搜索了第一个名称的一部分并产生了这个输出和一个空列表:
searching for first name: dam <-- This is the log print
Hibernate: select user0_.id as id1_6_, user0_.department as
departme2_6_, user0_.email as email3_6_, user0_.firstname as
firstnam4_6_, user0_.lastname as lastname5_6_, user0_.phone as
phone6_6_ from user user0_ where user0_.firstname like ?
精确匹配的搜索,返回带有一个对象的数组:
searching for first name: Adam
Hibernate: select user0_.id as id1_6_, user0_.department as
departme2_6_, user0_.email as email3_6_, user0_.firstname as
firstnam4_6_, user0_.lastname as lastname5_6_, user0_.phone as
phone6_6_ from user user0_ where user0_.firstname like ?
答案 0 :(得分:2)
尝试使用findByFirstnameContaining
代替findByFirstnameLike
。
我不确定如何解释like
。但是docs说:
Keyword | Sample | JPQL snippet
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %)
我想你想搜索%dam%
。
如果您想在开头或结尾处绑定通配符,也可以:findByFirstnameStartingWith
或findByFirstnameEndingWith
。
答案 1 :(得分:0)
关键字|样品JPQL代码段
喜欢| findByFirstnameLike…|其中x.firstname像?1
作为参数传递的值必须包含'%',例如:
列表ret = userRepo.findByFirstnameLike(name +“%”);