如何从 table --- JPA 或 CrudRepository 检索特定列?我只想从用户 table 检索电子邮件列

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

用户模型

@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() {}

    }

我对应的用户仓库:

    package hello.repository;

    import org.springframework.data.repository.CrudRepository;

    import hello.model.User;

    public interface UserRepository extends CrudRepository<User,Long> {

    }

在我的控制器中:

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

我发现这会检索整个用户 table.But 这不是我想要的。我的要求只是来自用户 table 的电子邮件列。

如何只检索来自用户 table 的电子邮件? ---> SQL 查询来自用户的 SELECT 电子邮件;

在您的 UserRepository 中使用 @Query 注释创建查询,如下所示:

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

并在你的控制器中调用它

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

如果您不想编写查询,您可以使用 projections 来检索您只需要的字段:

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);
}

所有这些查询方法 select 仅特定字段。对于上面示例中的投影,他们仅 select 电子邮件字段:

select p.email from users u ...

当然,您始终可以将自定义查询指定为 select 只有一个字段(如@AjitSoman 所说):

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

(我认为这里不需要重复值,所以我们应该在查询中使用distinct...)