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

时间:2015-10-03 15:38:55

标签: java spring hibernate spring-mvc

我在我的网址中传递了2个参数:名称和缩写。使用接受单个值的URL时,应用程序可以正常工作。

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

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

尝试使用其中任何一个网址。

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的这两个值?

更新

MS。那很有效。谢谢。在使用ParameterList之后,我得到了一个ORA-01797:此运算符必须后跟ANY或ALL。所以我改变了:进入。

2 个答案:

答案 0 :(得分:1)

如果您使用

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

并使用setParameterList方法添加参数

query.setParameterList("abbreviation", abbreviation);

一切都应该适合你。

另外,请注意@Roman在下面的评论中正确使用列表参数user.abbreviation in :abbreviation

答案 1 :(得分:-1)

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