MyBatis Delete Operation: Step-by-Step Guide
Performing a delete operation in MyBatis is usually achieved by using the delete tag. The specific steps are as follows:
- Write the SQL statement for a delete operation in the Mapper file of MyBatis, for example:
<delete id="deleteUserById" parameterType="int">
DELETE FROM user
WHERE id = #{id}
</delete>
- In Java code, calling the method of the Mapper interface to perform delete operation, for example:
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteUserById(1);
sqlSession.commit();
} finally {
sqlSession.close();
}
In the above example, we first obtained an instance of the Mapper interface using sqlSession.getMapper(UserMapper.class) method, then called the deleteUserById method to perform the deletion operation, and finally committed the transaction using sqlSession.commit() method.