有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用RequestParam通过Hibernate传递多个值?

我正在我的url中传递两个参数:名称和缩写。当使用此URL接受单个值时,应用程序工作正常

http://localhost:8080/userSearch/locate?name=John&abbreviation=F

现在我需要缩写来处理多个值F,M

正在尝试使用这些URL之一

http://localhost:8080/userSearch/locate?name=John&abbreviation=F&abbreviation=M
http://localhost:8080/userSearch/locate?name=John&abbreviation=F,M

当传递多个值时,我得到一个空字符串[]。我查看了查询,我认为HQL参数中的缩写设置不正确。我看到F和M被传递给方法,我尝试使用

String resultString = Arrays.toString(status);

和/或

 StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < status.length; i++) {
       strBuilder.append( abbreviation[i] );
    }
    String resultString = strBuilder.toString();

下面的代码:

控制器

public List<Users> findUser(
  @RequestParam(value = "name") String name,
  @RequestParam(value = "abbreviation") String[] abbreviation
       throws Exception{

 List<Users> users=new ArrayList<Users>();
  users= userService.getUser(name, abbreviation);

 return users;
 }

服务

public List<Users> getUser(String name, String[] abbreviation)
 throws Exception {     
    return UserImpl.locateUser(name, abbreviation);
}

Impl

public List<User> locateUser(String name, String[] abbreviation ) throws Exception {

    String resultString = Arrays.toString(status);
    //or
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < status.length; i++) {
       strBuilder.append( status[i] );
    }

    String statusResults = strBuilder.toString();

        StringBuffer sql = new StringBuffer();
        sql.append("select user, con "                          
                + " from User user, Contacts con "          
                + " where user.userId = con.userId");

            sql.append( " and user.name =:name " );

            //works with single value
            sql.append( "  and user.abbreviation =:abbreviation " );

            //does not work with multiple value
            sql.append( "  and user.abbreviation =:resultString " );


        Query qry = factory.getCurrentSession().createQuery(sql.toString());
        qry.setParameter("name", name);

        //works with single value
        query.setParameter("abbreviation", abbreviation);

        //doesn't work with multiple value (Returns an empty string [])
        query.setParameter("resultString", resultString);

   List<Object[]> userList = query.list();

如何处理来自URL的这两个值

更新

女士,这很有效。谢谢在使用参数列表后,我得到了一个ORA-01797:这个操作符后面必须跟有任何或全部。所以我改了:加入


共 (2) 个答案

  1. # 1 楼答案

    如果你使用

    http://localhost:8080/userSearch/locate?name=John&abbreviation=F&abbreviation=M

    并使用setParameterList方法添加参数

    query.setParameterList("abbreviation", abbreviation);

    一切都应该对你有用

    另外,请注意列表参数user.abbreviation in :abbreviation的正确用法,如@Roman在下面的注释中所述

  2. # 2 楼答案

    尝试将@RequestParam(value = "abbreviation") String[] abbreviation更改为@RequestParam(value = "abbreviation") String abbreviation。然后使用String[] args = abbreviation.split(",")拆分字符串