Hibernate criteria.list bad results with quotes and accents - java

I'm using hibernate 3.6 and i'm having problems using criteria.list. I need search words with quotes or accents like "d'eau" or "d´eau". My code is something like this:
Criteria criteria;
criteria.add(Restrictions.ilike("nameParam", "d''eau", MatchMode.ANYWHERE));
I put two single quotes because i'm working with a sql server database. There are 2 single quotes because single quote escapes with another single quote.
The statement has 0 results, but if I execute the sql statement printed in the log in the sql server client, I get 120 results aprox.
Testing with HQL and the same sql statement. I get this:
String hqlQuery = "select distinct(t) from Table t where b.idCon in (select t2.idCon from Table t2 where lower(t2.outTerTb) like '%d''eau%')";
List qwer = getEntityManager().createQuery(hqlQuery).getResultList();
System.out.println("qwer.size() -> " + qwer.size());
String hqlQuery2 = "select distinct(t) from Table t where b.idCon in (select t2.idCon from Table t2 where lower(t2.outTerTb) like :param)";
List qwer2 = getEntityManager().createQuery(hqlQuery2).setParameter("param", "%d''eau%").getResultList();
System.out.println("qwer2.size() -> " + qwer2.size());
This code print:
qwer.size() -> 120
qwer2.size() -> 0
And I don't understand why this happens.
Sorry if my english is bad

You don't need to escape single quotes in your parameters. That's the whole point of using parameters (in Hibernate and, behind the scenes, in the JDBC prepared statements): the JDBC driver escapes everything that needs to be escaped for you.
You take what comes from the UI layer as is and stuff it into parameters, everything isproperly escaped by the driver, and you don't risk any SQL injection attack.

Related

Single Quote issue with Oracle 12 C JDBC [duplicate]

I'm having issues dealing with the single quote while using it in a prepared statement in JAVA via Oracle JDBC.
Let's say we have a table Restaurant with a column restaurant_name with 1 value : Jack's Deli
I want to use a simple prepared statement query like this:
String result = "Jack\'\'s Deli"
String sqlStatement = "select * from Restaurant where restauraunt_name like ? escape '\\' ";
PreparedStatement pStmt = conn.prepareStatement(sqlStatement);
pstmt.setString(1, result);
The result shows 0 returned values, however when I directly search the query in the database (ORACLE) it works fine and retrieves the result. (Oracle uses two single quotes as an escape for the first)
I am thinking that the value is not being passed properly to the database. Or there is some other formatting issue.
The point of prepared statements is that you don't need any escaping.
.setString(1, "Jack's Deli") will get it done.

Concatenating a SQL string query in a JSP file

I have a html page that allows users to enter specific search terms to query the database I've created. The problem I'm having is that when I pass the string to execute as a sql query, it is not wrapping the query in single quotes which is needed to search for a string match in a sql database. Here is the code I have currently:
//Create a statement for the sql queries
java.sql.Statement stmt = conn.createStatement();
//Get results from queries entered
String result_event_name = request.getParameter("event_name");
//Create query string
String sqlQuery_event = "SELECT event_name FROM event where event_name = " + "\'" + result_event_name + "\'";
//execute query
java.sql.ResultSet rs_event = stmt.executeQuery(sqlQuery_event);`
This is the error I get:
SQLException: ERROR: syntax error at end of input Position: 49
I tried using prepare statement -- returns same error
I tried the query without escaping -- returns same error
I tried with no single quotes -- returns same error
The single quote ' only needs escaping once LIKE '%\'%'
But to query backslash \ you need to double escape to LIKE '%\\\\%'
If you wanted to query backslash+singlequote \' then LIKE '%\\\\\'%'
(with 5 backslashes)
Explanation Source excerpt:
Because MySQL uses C escape syntax in strings (for example, “\n” to
represent a newline character), you must double any “\” that you use
in LIKE strings. For example, to search for “\n”, specify it as “\n”.
To search for “\”, specify it as “\”; this is because the backslashes
are stripped once by the parser and again when the pattern match is
made, leaving a single backslash to be matched against.
Credit goes to xchiltonx
Resource Link:
mysql - How to handle query search with special characters /(forward slash) and \(backslash)

jpql left join fetch not returning results for like

In a spring mvc app using hibernate and MySQL, I have written the following query method to return a list of names with patients:
#SuppressWarnings("unchecked")
public Collection<Person> findPersonByLastName(String ln) throws DataAccessException{
Query query = this.em.createQuery("SELECT DISTINCT pers FROM rimPerson pers left join fetch pers.names nm WHERE nm.family LIKE :lnm");
query.setParameter("lnm", ln);
return query.getResultList();
}
This is producing the following hibernate sql:
Hibernate:
select distinct
person0_.hppid as hppid1_340_0_,
names1_.HJID as HJID1_89_1_,
person0_2_.classCode_HJID as classCod2_339_0_,
person0_1_.administrativeGenderCode_HJID as administ2_341_0_,
person0_1_.birthTime_HJID as birthTim3_341_0_,
names1_.DELIMITER_ as DELIMITE2_89_1_,
names1_.FAMILY as FAMILY3_89_1_,
names1_.named_entity_hppid as named5_89_1_,
names1_.SUFFIX as SUFFIX4_89_1_,
names1_.name_entity_HJID as name9_340_0__,
names1_.HJID as HJID1_89_0__
from
rim_person person0_ inner join rim_living_subject person0_1_ on person0_.hppid=person0_1_.hppid
inner join rim_entity person0_2_ on person0_.hppid=person0_2_.hppid
inner join rim_infrastructure_root person0_3_ on person0_.hppid=person0_3_.hppid
left outer join EN names1_ on person0_.hppid=names1_.name_entity_HJID
where names1_.FAMILY like ?
When I call the above jpql method with the following command, it returns zero results:
this.myappService.findPersonByLastName("");
I also get zero results when I cut and past the above generated hibernate code into the MySQL command line client and replace ? with ''.
If, however, I remove the where names1_.FAMILY like ? from the hibernate generated sql above and place the shortened sql into the MySQL command line client, I get four results, eachof which has a value for the lastname field.
How can I change the jpql so that it generates a hibernate query that returns the four results when `` is passed as the empty string parameter? I want the result set to include every result when the user gives empty input, but to give filtered results when the user types in any given text input.
The typical reason that like fails to do what you think it ought to do is to forget to put a wildcard in the pattern string. For example, if you want to match all user names that begin with 'Code' you must do something like name like 'Code%', NOT name like 'Code'. You can control exactly what your predicate matches with careful placement of %s in your string.
Try this to see all entities no matter what the value in family:
this.myappService.findPersonByLastName("%");
It is kinda cheesy to have the caller of findPersionByLastName have to put in the % wildcard. A better implementation is to have the caller specify which last name they are looking for, and then have the code that constructs the query put the wildcard in the right place. When you are looking for last names, you might do something like this:
query.setParameter("lnm", "%" + ln);
That would match anything that ends with the parameter that is passed to the method.

Executing a sql server query containing clause " where col like N'myStr%' " from java using spring

my query works using sql server management studio. However I can not get the query to work with named parameters and springsJDBCTemplate.
So actual sql required that works fine :
select colA from table1 where colb like N'lem%'
and a snippet of what I have tried :
String paramA = "N'lem%'";
select colA from table1 where colb like :paramA
I am using springs namedParamterJDBCTemplate. The N specifies nvarchar and unicode encoding as the actual parameters are encoded in foreign languages, eg cyrillic.
N' is useful when presenting some text to the textual SQL parser in SSMS, but when you are using parameterised queries through spring, DON'T! The string itself should be in Unicode, and the framework with handle it for you by declaring the parameter as NVarchar as well as marshalling the param properly.
String paramA = "lem%";
I don't believe you should even have the single quotes in the string, which I understand you're including only because of the N' notation.
You might want to try escape sequence for
String paramA = "N\'lem%'";
http://docs.oracle.com/javase/tutorial/java/data/characters.html

I have stuck with the simplest SQL query in java

I can't find the correct syntax of the following query in java,please help me.
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"' ";
String st = "SELECT COUNT('"+id+"') FROM '"+selected_table+"'";
I think that the mistake is how to end the query...
Since I got the error Check the manual that corresponds to your MySQL server version for the right syntax to use near ''Customer'' at line 1
when I choose Customer table
You want to use backticks instead of single quotes around your object names.
String st = "SELECT COUNT(`"+id+"`) FROM `"+selected_table+"` ";
Table names should be surrounded by tick marks (`), not single quotes (')
String st = "SELECT COUNT('"+id+"') FROM `"+selected_table+"`";
^ use tick marks ^
What are the values of id and selected_table? What is the actual query string that is sent to the database?
Also, it's rarely a good idea to manually build a query like this using string concatenation. This makes it very easy for a bug to result in a gaping security hole, and it's a lot more difficult (and risky) to try to secure this approach than it is to just do it right.
Looks from your query that you are enclosing your id and selected_table in single quotes... For example, SELECT COUNT('ID') FROM 'CUSTOMER' which is wrong. should be in backtics `` or nothing...

Categories