在验证时查找有关查询用户的一些反馈。我在编写下面代码时的第一个想法是通过查询数据库中的所有用户名并检查提供的用户名是否属于用户列表来获取用户名。当用户表增长时,这种类型的检查会成为性能问题吗?
EntityManager entityManager = factory.createEntityManager();
/*Create a data structure to hold a list of users in our database*/
List<String> allUsernames = new ArrayList<String>();
allUsernames = entityManager.createQuery("SELECT user.username FROM Users user").getResultList();
/*Loop through each user in our available usernames checking if the username passed exists*/
for (String user : allUsernames) {
if (user.equals(username)) {
System.out.println("Found real user\n");
userFoundFLAG = 1; // set the flag equal to 1 when this user is found
}
}
答案 0 :(得分:1)
是的,这将是一个性能问题,随着用户数量的增加,这个问题越来越多。绝对不要这样做。
您应该执行以下操作:
try {
User user = (User)entityManager.createQuery("SELECT user FROM Users user where user.username = :username")
.setParameter ("username", username);
.getSingleResult();
userFoundFLAG = 1;
} catch (NoResultException e) {
//There is no user with this username - do something
} catch (NonUniqueResultException e) {
//There is more than one user with this username - do something
}
答案 1 :(得分:0)
为什么不按名称查询用户?如果返回非零列表,则用户存在,否则不存在。更好的是,为什么不只是读取整个用户对象,因为可以想象,您需要它来获得额外的身份验证/授权逻辑?
final TypedQuery<String> query = entityManager
.createQuery("SELECT u.username FROM Users u WHERE u.username = :username", String.class);
query.setParameter("username", "BillyBob");
if (query.getResultList().size() > 0) {
// ...
}
或者:
final TypedQuery<User> query = entityManager
.createQuery("SELECT u FROM Users u WHERE u.username = :username");
query.setParameter("username", "BillyBob");
final User user = query.getFirstResult();