How to execute update operations in MyBatis?
There are two ways to perform update operations in MyBatis.
- Use the insert, update, and delete tags: Define the corresponding SQL statements in the mapper file by using the insert, update, and delete tags, and then call the SqlSession’s insert, update, delete methods in the Java code to perform the update operations.
<!-- 定义更新语句 -->
<update id="updateUser" parameterType="User">
UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}
</update>
// 调用更新操作
User user = new User();
user.setId(1);
user.setUsername("newUsername");
user.setPassword("newPassword");
sqlSession.update("updateUser", user);
- By using the @Update annotation: define the update SQL statement in the mapper interface using the @Update annotation, and then call the corresponding mapper method in the Java code to execute the update operation.
@Update("UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}")
void updateUser(User user);
// 调用更新操作
User user = new User();
user.setId(1);
user.setUsername("newUsername");
user.setPassword("newPassword");
userMapper.updateUser(user);
These are the two ways to perform update operations in MyBatis. You can choose the appropriate method based on personal preference and project requirements.