继上
http://www.cnblogs.com/tk55/p/6659285.html
http://www.cnblogs.com/tk55/p/6660477.html
注解
将id:8 name: 小A age:54修改 name:大A age:44
UserMapper.java
package com.ij34.model; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; public interface UserMapper { @Select("select * from users where id=#{id}") public User selectUser(int id); @Update("update users set name=#{name},age=#{age} where id=#{id}") public void updateUser(User user); }
Test.java
package com.ij34.bean; import java.io.IOException; import java.io.InputStream; 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 com.ij34.model.User; import com.ij34.model.UserMapper; public class Test { public static void main(String[] args) throws IOException { String resource ="com/ij34/mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=sqlSessionFactory.openSession(); try { // List<User> users=session.selectList("com.ij34.mybatis.UserMapper.selectUser"); UserMapper mapper=session.getMapper(UserMapper.class); User user= mapper.selectUser(8); user.setAge(44); user.setName("大A"); mapper.updateUser(user); session.commit(); System.out.println(user); } finally { // TODO: handle finally clause session.close(); } } }
结果
XML
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ij34.mybatis.UserMapper"> <select id="selectUser" parameterType="int" resultType="com.ij34.model.User"> select * from users where id=#{id}; </select> <update id="updateUser" keyProperty="id"> update users set name=#{name},age=#{age} where id=#{id} </update> </mapper>
Test.java
package com.ij34.bean; import java.io.IOException; import java.io.InputStream; 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 com.ij34.model.User; public class Test { public static void main(String[] args) throws IOException { String resource ="com/ij34/mybatis/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session=sqlSessionFactory.openSession(); try { User user=session.selectOne("com.ij34.mybatis.UserMapper.selectUser", 8); //选择 user.setName("小小A"); user.setAge(24); session.update("com.ij34.mybatis.UserMapper.updateUser", user); // 更改 session.commit(); System.out.println(user); } finally { // TODO: handle finally clause session.close(); } } }