Learner Learner - 4 months ago 10
SQL Question

display online users only when isAdmin is true

I am creating an online chat application with Spring Boot application. I am able to display all the online users with the following code

Code snippets from my UserDao.java class

public List getAll() {
return getSession().createQuery("from User").list();
}


Controller calling the UserDao.java method for retrieving all

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


is there a way I can display all the users only when is admin is set to true.

Users.java bean class

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


Please how can I retrieve all the Users only when isAdmin is set to true instead of just displaying all the users.

spa spa
Answer

Should be possible with

public List getAll() {
    return getSession().createQuery("SELECT u FROM User u WHERE u.isAdmin = true").list();
}

Disclaimer: Didn't check the code.

Comments