本章将通过实例介绍怎样利用 <update> 更新数据库数据。本实例将根据用户ID修改指定用户的name、sex和age信息。Mapper XML 定义如下:
<update id="updateUser"> UPDATE `user` SET `name`=#{name, jdbcType=VARCHAR}, `sex`=#{sex, jdbcType=VARCHAR}, `age`=#{age, jdbcType=INTEGER} WHERE `user_id`=#{userId,jdbcType=INTEGER} </update>
(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/update/demo1/UserMapper.xml" /> </mappers> </configuration>
(2)定义 UserMapper.java 接口文件内容如下:
package com.hxstrive.mybatis.update.demo1; public interface UserMapper { /** * 更新用户信息 * @param userBean * @return */ int updateUser(UserBean userBean); }
(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.update.demo1.UserMapper"> <!-- 使用update实现更新数据的操作,注意:其他属性的用法见insert标签 --> <update id="updateUser"> UPDATE `user` SET `name`=#{name, jdbcType=VARCHAR}, `sex`=#{sex, jdbcType=VARCHAR}, `age`=#{age, jdbcType=INTEGER} WHERE `user_id`=#{userId,jdbcType=INTEGER} </update> </mapper>
(4)客户端代码如下:
package com.hxstrive.mybatis.update.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 UpdateDemo1 { public static void main(String[] args) throws Exception { // 获取 Mapper 对象 String cfgName = "com/hxstrive/mybatis/update/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); UserBean userBean = new UserBean(); userBean.setUserId(1); userBean.setName("张三"); userBean.setSex("男"); userBean.setAge(30); int result = userMapper.updateUser(userBean); System.out.println("result=" + result); } }