我正在使用Spring Boot应用程序创建在线聊天应用程序。我可以使用以下代码显示所有在线用户
来自UserDao.java类的代码段
public List getAll() {
return getSession().createQuery("from User").list();
}
控制器调用UserDao.java方法检索所有
@ResponseBody
@RequestMapping(value = "/get-all-users", method = RequestMethod.GET)
public List<User> getAllUsers() {
try {
return _userDao.getAll();
} catch (Exception e) {
logger.error("Exception in fetching users: ", e.getStackTrace());
}
return null;
}
有一种方法我只有在admin设置为true时才能显示所有用户。
Users.java bean类
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "userId")
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private long timestamp;
@Column(nullable = true)
private boolean isAdmin;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this.id == null || obj == null || !(this.getClass().equals(obj.getClass()))) {
return false;
}
User that = (User) obj;
return this.id.equals(that.getId());
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
如果isAdmin设置为true而不是仅显示所有用户,请该如何检索所有用户。
答案 0 :(得分:1)
应该可以
public List getAll() {
return getSession().createQuery("SELECT u FROM User u WHERE u.isAdmin = true").list();
}
免责声明:未检查代码。