Java + JPA:在数据库中搜索用户按名字和姓氏返回太多结果。有没有更好的办法?

时间:2011-01-19 07:57:08

标签: java mysql database jpa jpa-2.0

现在我的实现是这样的,所以如果用户类型是Peter Smith,那么我会对查询字符串进行拆分,如下所示:

String[] name = searchQuery.split(" "); //searchQuery is type String

然后我会遍历name array,对于每个name,我将其与我的数据库中的名字和姓氏字段匹配,如下所示

@NamedQuery(name="User.findUserByName",
    query="select c from User c where c.fname LIKE :param OR c.lname LIKE :param"),

public List<User> findUser(String searchParam){
    Query query = em.createNamedQuery("User.findUserByName");
    query.setParameter("param", "%" + searchParam + "%");
    return query.getResultList();
}

但是,如果我这样做,它会返回太多结果(与Peter相关的每件事都会显示出来,而与史密斯有关的一切也会如此)。有更好的方法吗?

我正在使用EclipseLink btw

1 个答案:

答案 0 :(得分:3)

如果我是你,我会使用Criteria API。这是一个示例实现:

public List<User> findUsersByName(final String firstName,
    final String lastName){

    final boolean hasFirst = firstName != null && firstName.length() > 0;
    // if you use Apache Commons / Lang, do it like this:
    // final boolean hasFirst = StringUtils.isNotBlank(firstName);

    final boolean hasLast = lastName != null && lastName.length() > 0;
    if(!hasFirst && !hasLast){
        // or throw IllegalArgumentException
        return Collections.emptyList();
    }
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<User> query = cb.createQuery(User.class);
    final Root<User> root = query.from(User.class);
    if(hasFirst && hasLast){
        query.where(cb.and(
            likeExpression(cb, root,"lname", lastName),
            likeExpression(cb, root, "fname", firstName)
            ));
    } else if(hasFirst){
        query.where(likeExpression(cb, root,"fname", firstName));
    } else{
        query.where(likeExpression(cb, root,"lname", lastName));
    }
    return em.createQuery(query).getResultList();
}

private static Predicate likeExpression(final CriteriaBuilder cb,
    final Root<User> root,
    final String path, String parameter){
    return cb.like(root.<String> get(path), "*"+parameter.trim()+"*");
}

现在您可以轻松创建此方法的重载版本:

public List<User> findUsersByFullName(final String fullName){
    final String[] parts = fullName.split("\\s+");
    if(parts.length != 2){
        // probably you should assemble first name from all parts
        // except the last, but I'm lazy
        throw new IllegalArgumentException("Bad name: " + fullName);
    }
    return findUsersByName(parts[0], parts[1]);
}

public List<User> findUsersByLastName(final String lastName){
    return findUsersByName(null, lastName);
}

public List<User> findUsersByFirstName(final String firstName){
    return findUsersByName(firstName, null);
}

参考: