用户模型
@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> {
}
在我的 Controller 中:
@GetMapping(path="/all")
public @ResponseBody Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
我发现这会检索整个用户表。但这不是我想要的。我的要求只是用户表中的电子邮件列。
如何从用户表中只检索电子邮件? ---> SQL 查询,例如来自用户的 SELECT 电子邮件;
最佳答案
在您的 UserRepository
中使用 @Query
注释创建查询,如下所示:
public interface UserRepository extends CrudRepository<User,Long> {
@Query("select u.email from User u")
List<String> getAllEmail();
}
并在你的 Controller 中调用它
@GetMapping(path="/user/email")
public @ResponseBody List<String> getAllEmail() {
return userRepository.getAllEmail();
}
关于mysql - 如何从表中检索特定列 --- JPA 或 CrudRepository?我只想从用户表中检索电子邮件列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48366355/