【问题标题】:HOw to get result from subquery as param in query如何从子查询中获取结果作为查询中的参数
【发布时间】:2019-03-25 11:38:22
【问题描述】:

如何编写查询,以便我想将子查询的结果设置为主查询的参数。 书面查询在 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);
}

【问题讨论】:

    标签: jpa spring-data-jpa nativequery


    【解决方案1】:

    首先我从子查询中获取结果,然后将其存储在 java 代码中的变量中。之后将该变量用于主查询。

    int role_id=userRoleRepository.findIdByRole(user_type);
            int res = userRepository.authenticateUser(username, password,role_id);
            System.out.println("Query Result: "+res);
    

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 2014-08-25
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2013-04-07
      相关资源
      最近更新 更多