I'd like to use MyBatis3 only to produce SQL string (using the xml mapping) but the SQL i obtain is not valid.
Example, I obtain the sql string:
SELECT * FROM USER WHERE NAME = john
In this sql isn't present the ' char sorrounding the string value john
in mybatis.xml:
...
<mappers>
<mapper resource="sql1.xml"/>
</mappers>
...
sql1.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="sql1">
<select id="select1" parameterType="map" resultType="String" >
SELECT * FROM USERS
WHERE
name LIKE ${name} AND num = ${number}
</select>
</mapper>
in MyBatisSql.java:
SqlSessionFactory sessionFactory = ConnectionFactory.getSqlSessionFactory();
Configuration configuration = sessionFactory.getConfiguration();
Map pars = new HashMap<String, Object>();
pars.put("name", "john");
pars.put("number", 1345);
MappedStatement ms = configuration.getMappedStatement("sql1.select1);
BoundSql boundSql = ms.getBoundSql(params);
String sql = boundSql.getSql();
System.out.println(sql);
the result is
SELECT * FROM USERS
WHERE
name LIKE john AND num = 12345
in this SQL, the string john, isn't enclosed by the ' char so it's not a valid SQL (my purpose is only to produce valid SQL string using myBatis). I'd like to have:
SELECT * FROM USERS
WHERE
name LIKE 'john' AND num = 12345
thanks
The resultMap element is the most important and powerful element in MyBatis. It's what allows you to do away with 90% of the code that JDBC requires to retrieve data from ResultSet s, and in some cases allows you to do things that JDBC does not even support.
Dynamic SQL is a very powerful feature of MyBatis. It enables programmers to build queries based on the scenario dynamically. For example, if you want to search the Student data base, based on the name of the student in MyBatis, you have to write the query using the dynamic SQL.
typeHandlers. Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a value from a ResultSet, a TypeHandler is used to retrieve the value in a means appropriate to the Java type.
You should use #{name} instead of ${name}.
The sample below will generate a valid SQL
<mapper namespace="sql1">
<select id="select1" parameterType="map" resultType="String" >
SELECT * FROM USERS
WHERE
name LIKE #{name} AND num = #{number}
</select>
</mapper>
MyBatis directly copies and pastes the string parameter if you use $ character. On the other hand it uses parameter binding if you use # character.
You should then execute your sql using selectMap, selectList or selectOne,
List<String> resultSet = sessionFactory.openSession().selectList("sql1.select1", pars);
This call will automatically bind the parameters to the statement and execute it.
WARNING:
<select id="select1" parameterType="map" resultType="String" >
SELECT * FROM USERS
WHERE
name LIKE #{name} AND num = #{number}
</select>
might fail to execute since MyBatis cannot map multiple columns (SELECT *) to a single string (resultType="String") two possible corrections to the query is shown below:
<!--Solution One-->
<select id="select1" parameterType="map" resultType="String" >
SELECT name FROM USERS
WHERE
name LIKE #{name} AND num = #{number}
</select>
<!--Solution Two-->
<select id="select1" parameterType="map" resultType="java.util.LinkedHashMap" >
SELECT * FROM USERS
WHERE
name LIKE #{name} AND num = #{number}
</select>
For solution two you should execute mybatis query using the java code below:
List<Map<?, ?>> resultSet = sessionFactory.openSession().selectList("sql1.select1", pars);
Parameter binding is done at driver level so you will not get an sql string like this
SELECT * FROM USERS
WHERE
name LIKE 'john' AND num = 12345
Instead you'll get sql query template which is ready for parameter binding,
SELECT * FROM USERS
WHERE
name LIKE ? AND num = ?
Adding parameters into sql string allows sql injection. Safe way is to use parameter binding method provided with SQL Driver and MyBatis always uses parameter binding.
Suppose that you manually created your sql command as string, and suppose that I'm a malicius user trying to access your data. I can write
john' or ''='
So this will generate the sql command below:
SELECT * FROM USERS
WHERE
name LIKE 'john' or ''='' AND num = 12345
The second benefit of parameter binding is that it allows prepared statements. Suppose that you need to execute same sql 1000 times with different parameters.
If you generate sql strings with parameters bound,
SELECT * FROM USERS WHERE name LIKE 'john' AND num = 12345;
SELECT * FROM USERS WHERE name LIKE 'foo' AND num = 67890;
database server will need to parse each sql command one by one and then execute them.
With parameterized sql queries,
SELECT * FROM USERS WHERE name LIKE ? AND num = ?
SQL driver caches the query so parsing is done only once and then it binds different parameters to the same SQL command.
You can still use the parameterized sql (boundSql) with an another library or Java's java.sql.Connection. Below is an example:
Connection myConnection;
PreparedStatement preparedStatement = myConnection.prepareStatement(boundSql);
preparedStatement.setString(1, "john"); //First parameter starts with 1 not 0!
preparedStatement.setInt(2, 12345);
ResultSet results = preparedStatement.executeQuery();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With