Unable to locate appropriate constructor error for nested list object in kotlin and JpaRepository

后端 未结 3 1762
刺人心
刺人心 2021-01-25 15:10

I\'m facing the following error when JPA attempts to map the result from a query to the result repository method DTO:

org.hibernate.hql.internal.ast.QuerySyntaxE         


        
3条回答
  •  日久生厌
    2021-01-25 15:57

    The problem is that database query is able to return plain result only. Persistence provider can convert it to entities with nested entities lists. As for dto you have to solve the problem yourself.

    So you can get plain result using User dto with constructor as below

    public User(String username, String password, String roleName, String roleDescription) {
         this.username = username;
         this.password = password;
         roles = new ArrayList<>();
         roles.add(new Role(roleName, roleDescription));  
    }
    

    Then you need repository method like this

    @Query("select new com.example.dto.User(u.username, u.password, r.roleName, r.description) from DbUser u join u.roles r where u.username=:username")
    List findUserByUsername(@Param("username") String username);
    

    Handle result in service layer

    public Optional findUserByUsername(username) {
        List users = findUserByUsername(username);
    
        if(users.isEmpty()) {
            return Optional.empty();
        }
    
        User user = users.get(0);
        if(users.size() > 1) {
             users.subList(1, users.size()).forEach(u -> user.getRoles().addAll(u.getRoles()));
        }
    
        return Optional.of(user);
    }
    

    You can use the same approach for Kotlin

提交回复
热议问题