简体   繁体   English

该JPA查询出了什么问题,需要通过特定名称查找用户

[英]What's wrong with that JPA query, need to find a user by specific name

I have a method that search a name, when the user passes a parameter. 当用户传递参数时,我有一种搜索名称的方法。 Now I need a method to tell me what's the employee's role in the company 现在我需要一种方法来告诉我员工在公司中的角色是什么

The idea is to take this data and insert into a combobox. 想法是获取此数据并将其插入组合框。

This is the method that i used to find the names passes by parameter: 这是我用来查找名称的方法,它通过参数传递:

public List<User> findbyName(String name) { 
    EntityManager em = getEntityManager();
    String sql = "select u from User u where UPPER(u.name) like UPPER ('" + name + "%')";
    List<User> u = null;
    try {
        u = (List<User> ) em.createQuery(sql).getResultList();

    } catch (Exception e) {

        return null;          
    }
    return u;
}

And here is that method that im trying to do: 这是我正在尝试执行的方法:

public List<User>  findbyRole(){
    EntityManager em = getEntityManager();
            String sql = "select u from User u where UPPER(u.role) like (journalist)";
            List<User>  u = null;
    try {
        u = (List<User> ) em.createQuery(sql).getResultList();

    } catch (Exception e) {

        return null;          
    }
    return u;
}

Code to insert into combobox, its right? 要插入组合框的代码,对不对?

List <User> list= new UserJpaController().findbyRole();
     for(int i=0;i<lista.size();i++){
      combojournalist.addItem(list.get(i).getCargo());
}

If you want to use a literal string journalist in your query, you either need to put it into quotes, or pass it as parameter. 如果要在查询中使用文字字符串journalist ,则需要将其放在引号中,或将其作为参数传递。 Otherwise JPA would think that journalist is an alias, but such alias is not defined in the query. 否则,JPA会认为journalist是别名,但是在查询中未定义此类别名。

So your query should be like this (see quotes around journalist): 因此,您的查询应如下所示(请参阅新闻记者的引言):

select u from User u where UPPER(u.role) like ('journalist')

or if you use parameters, which is always a better option: 或者,如果您使用参数,则总是一个更好的选择:

String sql = "select u from User u where UPPER(u.role) like (:role)";
List<User>  u = em.createQuery(sql, User.class)
         .setParameter("role", "journalist")
         .getResultList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM