本章节将通过一个完整的实例介绍 <delete> 标签的用法。
(1)MyBatis 配置文件 mybatis-cfg.xml 内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/hxstrive/mybatis/delete/demo1/UserMapper.xml" /> </mappers> </configuration>
(2)定义 UserMapper.java 文件,代码如下:
package com.hxstrive.mybatis.delete.demo1; public interface UserMapper { /** * 更新用户信息 * @param userId 用户ID * @return */ int deleteUser(int userId); }
(3)定义 UserMapper.xml 文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.delete.demo1.UserMapper"> <!-- 使用update实现更新数据的操作,注意:其他属性的用法见insert标签 --> <delete id="deleteUser" parameterType="int"> DELETE FROM `user` WHERE `user_id`=#{userId, jdbcType=INTEGER} </delete> </mapper>
上面的 <delete> 标签中定义的 SQL 语句将根据 userId 从 user 表删除用户信息。
(4)客户端代码如下:
package com.hxstrive.mybatis.delete.demo1; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class DeleteDemo1 { public static void main(String[] args) throws Exception { // 获取 Mapper 对象 String cfgName = "com/hxstrive/mybatis/delete/demo1/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int result = userMapper.deleteUser(74506); System.out.println("result=" + result); } }