1

寻找一些关于在认证时查询用户的反馈。在编写下面的代码时,我的第一个想法是通过查询数据库中的所有用户名并检查提供的用户名是否属于用户列表来获取用户名。当用户表增长时,这种类型的检查会成为性能问题吗?

    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
        }

    }
4

2 回答 2

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
}
于 2012-04-18T00:21:29.663 回答
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();
于 2012-04-17T23:56:31.770 回答