Mybatisで特殊文字をエスケープ
特殊文字のエスケープ例
MyBatisでSQLインジェクションを防ぐため、特殊文字をエスケープする必要があります。
以下にtestTableというテーブルとtestEntityというクラスを使用した例を示します。
エンティティクラス (testEntity)
public class testEntity { private String name; // getterとsetter public String getName() { return name; } public void setName(String name) { this.name = name; } }
MyBatisのマッパー (testMapper.xml)
特殊文字をエスケープするために、MyBatisのescape関数を利用できます。
以下はselect文で特殊文字をエスケープする例です。
<mapper namespace="testMapper"> <select id="selectTestEntityByName" resultType="testEntity"> SELECT * FROM testTable WHERE name = #{name, jdbcType=VARCHAR, escape=true} </select> </mapper>
この例では、ユーザーが入力したnameフィールドの値に対して、特殊文字がエスケープされるようになっています。
escape=trueを指定することで、MyBatisが自動的に特殊文字をエスケープします。