简体   繁体   中英

How to retrieve specific column from the table — JPA or CrudRepository? I want to retreive only email column from user table

User Model

@Entity
@Table(name = "user",uniqueConstraints = {@UniqueConstraint(columnNames = {"email"}) })
public class User implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 382892255440680084L;

    private int id;
    private String email;
    private String userName;

    private Set<Role> roles = new HashSet<Role>();

    public User() {}

    }

My corresponding User repo:

    package hello.repository;

    import org.springframework.data.repository.CrudRepository;

    import hello.model.User;

    public interface UserRepository extends CrudRepository<User,Long> {

    }

In the controller I do :

@GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }

I find that this retrieves the entire user table.But this is not what I want. My requirement is only email column from the user table.

How do I retrieve only email from user table? ---> SQL Query like SELECT email from user;

Create a query using @Query annoatation in your UserRepository like this:

public interface UserRepository extends CrudRepository<User,Long> {
   @Query("select u.email from User u")
   List<String> getAllEmail();
}

And call it in your controller

@GetMapping(path="/user/email")
public @ResponseBody List<String> getAllEmail() {
    return userRepository.getAllEmail();
}

If you don't want to write a query you can use projections to retrieve fields you only need:

public interface UserProjection {
    String getEmail();
}

public interface UserRepo extends CrudRepository<User, Long> {
   List<UserProjection> getUserProjectionsBy();
   Projection getUserProjectionById(Long userId);

   // Even in dynamic way:
   <T> List<T> getUserProjectionsBy(Class<T> type);
   <T> T getUserProjectionById(Long userId, Class<T> type);
}

All those query methods select only specific fields. For that projection from the example above they select email field only:

select p.email from users u ...

Of course, you can always specify your custom query to select only one field (as @AjitSoman said):

@Query("select distinct u.email from User u)
List<String> getAllEmails();

(I think duplicate values are not necessary here, so we should use distinct in the query...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM