Home > Software engineering >  Spring Boot JPA - How can you fetch only the usernames from repository?
Spring Boot JPA - How can you fetch only the usernames from repository?

Time:07-31

How can you modify this function so it only returns the users' names?

public List<User> findAll() 
{
    List<User> users = new ArrayList<>();
    repository.findAll().forEach(users::add);
    return users;
}

CodePudding user response:

If your user class has getters you can dot access them instead of just returning the user

Like user.getName

You can also after adding each user to users iterate through them with the getter and return a List

CodePudding user response:

You can convert the users list you have into a list containing only names using Stream and pass it return.

If you want to do it with the new method;

Add a new method, call the method that takes existing users, and then you can extract the list of name field in one shot in this way:

public List<String> findAllOnlyNames() {
    List<User> users = findAll();
    return users.stream()
            .map(User::getName)
            .collect(Collectors.toList());
}
If you want to change the method as it is;
public List<String> findAll() {
    List<User> users = new ArrayList<>();
    repository.findAll().forEach(users::add);
    return users.stream()
            .map(User::getName)
            .collect(Collectors.toList());
}

CodePudding user response:

You can also create a new method on the repository:

interface UserRepository extends ... {
    @Query("select name from #{#entityName}")
    List<String> findAllUserName();
} 

Which would avoid returning the whole User entity when you don't need it.

See documentation: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

  • Related