我在Spring Boot应用程序中遇到与JPQL相关的问题。我遇到问题“参数索引无效!您似乎声明的查询方法参数太少了!” 。无法通过用户名和客户端代码获取记录。请检查我下面的Spring Boot Application代码片段。
Bean类UserClients.Java。
@Entity
@Table(name = "usersclients")
public class UserClients implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long ID;
@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userName", referencedColumnName = "userName")
private Users user;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "clientCode", referencedColumnName = "code")
private Clients client;
}
存储库类UserClientsRepository
@Repository
public interface UserClientsRepository extends CrudRepository<UserClients, Long> {
@Async
@Query(value = "from UserClients userCli join userCli.user user join userCli.client client where user.userName= ?0 and client.clientCode= ?1", nativeQuery = true)
UserClients fetchRecordByUserNameClient(String userName,String clientCode);
}
服务类UserClientsService
@Service
public class UserClientsService {
@Autowired
private UserClientsRepository userClientsRepository;
public UserClients fetchRecordByUserNameClient(String username, String clientCode) {
return userClientsRepository.fetchRecordByUserNameClient(username, clientCode);
}
}
Controller类AuthenticationController
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/token")
public class AuthenticationController {
@Autowired
private UserClientsService userClientsService;
@RequestMapping(value = "/android-generate-token", method = RequestMethod.POST)
public ApiResponse<AuthToken> loginActivity(@RequestBody LoginUserDto loginUser) {
try {
final UserClients userClients= userClientsService.fetchRecordByUserNameClient(loginUser.getUsername(),
loginUser.getClient());
if(userClients == null) {
return new ApiResponse<>(401, "failed", null);
}
return new ApiResponse<>(200, "success", new AuthToken(token, user.getUserName()));
} catch (AuthenticationException e) {
return new ApiResponse<>(401, e.getMessage(), null);
}
}
}
答案 0 :(得分:2)
您的查询是错误的。
1)您已将native = true设置为意味着要使用SQL。但是查询看起来像HQL
2)您应该使用命名参数。
此外,我不确定您要使用@Async实现什么。如果不返回Future对象,该查询将永远不会异步运行。
因此您的查询应如下所示:
@Repository
public interface UserClientsRepository extends CrudRepository<UserClients, Long> {
@Async
@Query("select userCli from UserClients userCli join userCli.user user join userCli.client client "+
"where user.userName= :userName and client.clientCode= :clientCode")
Future<UserClients> fetchRecordByUserNameClient(String userName,String clientCode);
}