MyBatisを使って、insertやupdate、delete時にnullを設定するとエラーとなったときの対処法をメモしておきます。例えば、以下のSQL文の#{name}
や#{tel}
にnullを設定するとTypeException
が発生します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<insert id="insertUser"> | |
INSERT INTO users (id, name, tel) | |
VALUES (#{id}, #{name}, #{tel}) | |
</insert> | |
<update id="updateUser"> | |
UPDATE users | |
SET name = #{name}, tel = #{tel} | |
WHERE id = #{id} | |
</update> | |
<delete id="deleteUser"> | |
DELETE FROM users | |
WHERE tel = #{tel} | |
</delete> |
jdbcType
を指定する必要がある
JDBCの仕様で、insertやupdate、deleteでnullが許可されている列を指定する場合、JDBCデータ型(jdbcType
)を指定する必要があります。サポートされているJDBCデータ型の一覧は、MyBatisのドキュメントに記載されています。nullだとカラムのデータ型がわからないので、きちんと定義してねってことのようです。
具体的に上記コードを書き直してみると、以下のようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<insert id="insertUser"> | |
INSERT INTO users (id, name, tel) | |
VALUES (#{id}, #{name, jdbcType=VARCHAR}, #{tel, jdbcType=INTEGER}) | |
</insert> | |
<update id="updateUser"> | |
UPDATE users | |
SET name = #{name, jdbcType=VARCHAR}, tel = #{tel, jdbcType=INTEGER} | |
WHERE id = #{id} | |
</update> | |
<delete id="deleteUser"> | |
DELETE FROM users | |
WHERE tel = #{tel, jdbcType=INTEGER} | |
</delete> |
まとめ
MyBatisでinsertやupdate、delete時にnullを設定するときは忘れずjdbcType
を設定しましょう。