Exclude column from result set in controller | Spring jpa data

I have a user entity:

public class SpringUsers implements Serializable {
    private String password;
    // other fields omitted
    @Basic
    @Column(name = "password")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

And its repository:

public interface SpringUsersRepository extends CrudRepository<SpringUsers, Integer> {
    SpringUsers findByUsername(String username);
    List<SpringUsers> findByUserId(Integer userId);
}

And I have a controller method that should get a list of all registered users with the same userId (internally used) as the authenticated user:

public List<SpringUsers> getRegisteredUsers() {
    CustomUserDetails authenticatedUserDetails = getCustomUserDetails();
    List<SpringUsers> registered = springUsersRepository.findByUserId(
        authenticatedUserDetails.getUserMyId());
    return registered.stream().map(v -> {
        v.setPassword(null);
        return v;
    }).collect(Collectors.toList());
}

I do not want to pass the password (even if it is encrypted) to the external interface - so I pass it to users and set the password to null, as you can see above.

However, I wonder if it’s possible to simply not include the user password in the query result in the first place?


Version Information:

Spring boot 1.4.0 & Hibernate 5.0.9.Final

+7
2

@Query :

// Include all fields you wanna query for using u.x syntax
// AFAIK there is no exclusion syntatic sugar
@Query("select u.id, u.username from SpringUsers u where u.id = ?1")
List<SpringUsers> findByUserId(Integer userId);

. , :

interface NoPasswordUser {
    Long getId();
    String getUsername();
    // Do not include getPassword();
}

:

public interface SpringUsersRepository extends CrudRepository<SpringUsers, Integer> {
    NoPasswordUser findByUsername(String username);
    List<NoPasswordUser> findByUserId(Integer userId);
}

, REST - . DTO, .

+9

, db, - . ( , ).

POJO

select new my.company.SafeUser(u.username, u.email) from User u

, , DTO , , . , , , .

+2

Source: https://habr.com/ru/post/1653446/