两个或多个参数的setParameter在Jpa中不起作用(Mysql注入)

时间:2015-07-14 07:56:00

标签: java hibernate jpa

大家好......我正在寻找一种方法来避免在jpa中注入mysql ..并且得到了一个很酷的链接http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-persistence-api-jpa ...并且可以在这里单个参数工作正常是代码......

            StringBuilder getCity = new StringBuilder();
            getCity.append("SELECT ");
            getCity.append(" CITY.* ");
            getCity.append("FROM  ");
            getCity.append(" CITY  ");
            getCity.append("WHERE ");
            getCity.append("CITY.NAME LIKE ?1");
            System.out.println(getCity.toString());
            getSearchQuery=entityManager.createNativeQuery(getCity.toString(),CityModel.class).setMaxResults(1);
            getSearchQuery.setParameter(1,QueryToSearch);
            City=(CityModel)getSearchQuery.getSingleResult();

这是另外两个参数的代码..

getCity.append("SELECT ");
            getCity.append(" CONCAT_WS('<br />',CITY.NAME,CITY.ADDRESS) ");
            getCity.append("FROM  ");
            getCity.append("CITY  ");
            getCity.append("WHERE ");
            getCity.append(" (CITY.NAME LIKE ");
            getCity.append(" ?1 OR CITY.ADDRESS LIKE ");
            getCity.append(" ?2)");
            getCity.append(" AND ");
            getCity.append(" CITY.STATUS=");
            getCity.append("'"+"ACTIVE"+"'");
            getCity.append(" AND CITY.TYPE= ?3");
            System.out.println(getCity.toString());
            getSearchQuery=entityManager.createNativeQuery(getCity.toString());
            getSearchQuery.setParameter(1,QueryToSearch);
            getSearchQuery.setParameter(2,QueryToSearch);
            getSearchQuery.setParameter(3,CityType);

注意:即使在第二个查询中也能正常工作,如果我只放一个LIKE ...(多个喜欢和参数不起作用)并且好奇好奇LIKE怎么样?1在查询中工作%Type%或%Type或Type :) < / p>

2 个答案:

答案 0 :(得分:1)

对于希望在jpa原生查询中喜欢的未来用户

错了一个......

 getSearchQuery.setParameter(1,QueryToSearch);
 getSearchQuery.setParameter(2,QueryToSearch);
 getSearchQuery.setParameter(3,CityType);

Right One

 getSearchQuery.setParameter(1,"%"+QueryToSearch+"%");
 getSearchQuery.setParameter(2,"%"+QueryToSearch+"%");
 getSearchQuery.setParameter(3,CityType);

答案 1 :(得分:0)

this帖子中查看已接受的答案。我希望它有所帮助。