Reputation: 55
I would like to write dynamic query where column name and column value might change in WHERE
clause of SELECT statement.
So far I have this:
Mapper.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="mypackage.PersonMapper">
<resultMap id="personMap" type="Person">
<id property="name" column="NAME"/>
<id property="lastname" column="LASTNAME"/>
</resultMap>
<select id="selectByColumnName" resultType="Person" resultMap="personMap"><![CDATA[
SELECT * FROM PERSON WHERE #{columnName} = #{columnValue}
]]></select>
</mapper>
Mapper interface:
public interface PersonMapper {
List<PersonModel> selectByColumnName(
@Param("columnName") String column, @Param("columnValue") String value
);
}
But when I call it personMapper.selectByColumnName("NAME", "John")
, it does not work and gives me empty result. If I replace my SELECT query in Mapper.xml with query where I specify column name like this :
SELECT * FROM PERSON WHERE NAME = #{columnValue}
then it works fine and returns all persons with the given dynamic columnValue.
Upvotes: 1
Views: 4432
Reputation: 1664
You have to use ${}
string substitution:
<select id="selectByColumnName" resultType="Person" resultMap="personMap"><![CDATA[
SELECT * FROM PERSON WHERE ${columnName} = #{columnValue}
]]></select>
Upvotes: 3