用户模型
@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();
}
我发现这会检索整个用户表。但这不是我想要的。我的要求只是用户表中的电子邮件列。
如何从用户表中仅检索电子邮件? ---> SQL 查询,例如从用户中选择电子邮件;
使用创建查询@Query
注释在你的UserRepository
像这样:
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)