How to delete table data in MyBatis?

MyBatis is a persistence framework used to interact with databases. To delete table data, you can follow the steps below:

  1. Configure database connection information in your MyBatis configuration file.
  2. Create a Java entity class that corresponds to a database table, with its properties matching the fields in the table.
  3. Create a Mapper interface to define methods for interacting with database tables.
  4. removeDataById
  5. Write SQL statements in the corresponding XML file in the Mapper to achieve the function of deleting data.
  6. By calling the method of the Mapper interface in Java code and passing in the parameters of the data to be deleted, the deletion operation can be achieved.

The specific code example is as follows:

  1. Create Java entity classes that correspond to database tables.
public class User {
    private Long id;
    private String name;
    // getter和setter方法
}
  1. Create a Mapper interface:
public interface UserMapper {
    void deleteDataById(Long id);
}
  1. Write the SQL statement in the XML file corresponding to the Mapper.
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
    <delete id="deleteDataById" parameterType="java.lang.Long">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>
  1. Use the SqlSessionFactory in Java code to obtain an instance of the Mapper interface, and call the method to delete data.
SqlSessionFactory sqlSessionFactory = ... // 创建SqlSessionFactory实例
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteDataById(1L); // 传入需要删除的数据的id
sqlSession.commit(); // 提交事务
sqlSession.close(); // 关闭会话

By following the above steps, you can use MyBatis to delete data from a database table.

广告
Closing in 10 seconds
bannerAds