gpt4 book ai didi

java - 使用 spring 查询方法出现意外的空结果

转载 作者:行者123 更新时间:2023-12-02 03:34:23 25 4
gpt4 key购买 nike

我正在使用 Spring Boot 和连接到 MySQL 数据库的 JPA 构建具有 REST API 的应用程序。为了在 User 类中搜索名称,我实现了一个查询方法:List< User > findByFirstnameLike( String name );

此方法仅返回完全匹配的结果,这不是我想要的。我是否误解了它的用途?

存储库接口(interface):

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接口(interface)方法:

@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:打开显示 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 ?

最佳答案

尝试使用findByFirstnameContaining而不是findByFirstnameLike

我不确定 like 是如何解释的。但是docs说:

Keyword     | Sample                    | JPQL snippet

Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %)

我想您想搜索%dam%

如果您想在开头或结尾绑定(bind)通配符,也可以这样做:findByFirstnameStartingWithfindByFirstnameEndingWith

关于java - 使用 spring 查询方法出现意外的空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37614490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com