如何编写查询,以便我想将子查询的结果设置为主查询的参数。 书面查询在PostgreSQL查询编辑器中可以正常工作,并将伪值设置为参数
错误日志:
org.hibernate.QueryException: Space is not allowed after parameter prefix ':'[select * from public.users as u where u.username=:username and u.password=:password and u.role_id=:(select id from public.user_roles as ur where ur.role=:user_type)]
at org.hibernate.engine.query.spi.ParameterParser.parse(ParameterParser.java:175) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]"
源代码:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.hcs.sws.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
@Query(value ="select * from public.users as u where u.username=:username and u.password=:password and u.role_id=:(select id from public.user_roles as ur where ur.role=:user_type)",nativeQuery=true)
public int authenticateUser(@Param("username") String username,@Param("password") String password,@Param("user_type") String user_type);
}
答案 0 :(得分:0)
首先我从子查询中获得结果,然后将其存储在Java代码中的变量中。之后,将该变量用于主查询。
int role_id=userRoleRepository.findIdByRole(user_type);
int res = userRepository.authenticateUser(username, password,role_id);
System.out.println("Query Result: "+res);