如何从表中检索特定的列-JPA或CrudRepository?我只想从用户表中检索电子邮件列 [英] How to retrieve specific column from the table --- JPA or CrudRepository? I want to retreive only email column from user table

查看:0
本文介绍了如何从表中检索特定的列-JPA或CrudRepository?我只想从用户表中检索电子邮件列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户模型

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

我发现这将检索整个用户表,但这不是我想要的。我的要求是只从用户表的电子邮件列。

如何仅从用户表中检索电子邮件?->类似于SELECT EMAIL FROM USER的SQL查询;

推荐答案

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

这篇关于如何从表中检索特定的列-JPA或CrudRepository?我只想从用户表中检索电子邮件列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆