How to use native SQL in MyBatis?
Using native SQL in MyBatis can be achieved by using tags such as
- Query data using raw SQL.
<select id="selectUserById" resultType="User" parameterType="int">
SELECT * FROM user WHERE id = #{id}
</select>
- Insert data using native SQL.
<insert id="insertUser" parameterType="User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
- Update the data using raw SQL queries.
<update id="updateUser" parameterType="User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
- Delete data using raw SQL.
<delete id="deleteUser" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
When calling these SQL statements, you can execute the corresponding SQL statements using MyBatis’ SqlSession interface methods such as selectOne(), insert(), update(), delete().