Gopi Lal
Gopi Lal

Reputation: 427

setParameter For Two Or More Arguments Not Working In Jpa (Mysql Injection)

Hello guys...i was looking a way to avoid mysql injection in jpa..and got a link http://software-security.sans.org/developer-how-to/fix-sql-injection-in-java-persistence-api-jpa which is cool...and works fine for single argument here is the code...

            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();

Here is the other code where two argument are there..

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);

NOTE:Works fine even in second query if i put only one LIKE...(Multiple like and argument not working) And Just curious how does LIKE ?1 in query works %Type% Or %Type Or Type :)

Upvotes: 1

Views: 1666

Answers (1)

Gopi Lal
Gopi Lal

Reputation: 427

For Future Users Who Wants LIKE in jpa Native Query

Wrong One...

 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);

Upvotes: 1

Related Questions