1

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.

1 Answer 1

3

You have to use ${} string substitution:

    <select id="selectByColumnName" resultType="Person" resultMap="personMap"><![CDATA[
        SELECT * FROM PERSON WHERE ${columnName} = #{columnValue}
    ]]></select>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.