Spring Boot JPA通过自定义字符串字段查找



我正试图获得一个基于自定义字符串字段的模型列表。在User类中,我希望搜索数据库并检索包含特定role值的所有模型。

型号等级

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; 
private String role;
...
}

存储库类

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
List<User> findById(@Param(value = "id") Long id);
List<User> findByRole(@Param(value = "role") String role);
}

服务等级

@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public List<User> getAllUsers() {
return userRepository.findAll();
}

public List<User> findUserById(@PathVariable("id") Long id){
return userRepository.findById(id);
}
public List<User> findUserByRole(String role){
return userRepository.findByRole(role);
}
...
}

控制器类

@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
UserService userService;
@GetMapping
public List<User> accessUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public List<User> findById(@PathVariable("id") Long id){
return userService.findUserById(id);
}
@GetMapping("/{role}")
public List<User> findByRole(@RequestParam(value="role") String role){
return userService.findUserByRole(role);
}
...
}

我提出如下请求(其中角色=经理(:

GET localhost:8080/api/users/MANAGER

然而,我得到了这个错误。我注意到,如果我试图基于Long-id值获取模型,它是有效的,但每当我尝试使用String字段时,它都会给出错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Ambiguous handler methods mapped for '/api/users/CHEF': {public java.util.Optional com.cs322.ors.controller.UserController.accessUserInfo(long,org.springframework.security.core.Authentication), public java.util.List com.cs322.ors.controller.UserController.findByRole(java.lang.String)}

我尝试了以下链接,但问题仍然存在:

  1. Spring引导模糊处理程序
  2. 使用Spring处理REST应用程序中映射的不明确处理程序方法

一个朋友帮我解决了这个问题。

在映射路由GET localhost:8080/api/users/MANAGER时,Spring Boot不知道我指定的是GET localhost:8080/api/users/{id}还是GET localhost:8080/api/users/{role}。由于它们具有相同的url,因此无法在idrole之间做出决定。为了解决这个问题,我添加了一个更具体的端点,如下所示:

@GetMapping("roles/{role}")
public List<User> findByRole(@PathVariable("role") String role){
return userService.findUserByRole(role);
}

相关内容

最新更新