Mybitis(iBitis)实现对对象增删改查操作要借助<select/>查询,<insert/>增加,<update/>更新,<delete/>删除 标签来操作。
值得注意的有两点:
1、在对对象进行增删改时,SqlSession session = sqlSessionFactory.openSession();获取的session。必选执行session.commit();否则操作无效。
2、Mybitis与hibernate一样,插入数据后会把id值赋值给缓存中对象
还是接着上一讲的代码继续改动
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="user">
- <resultMap id="userResultMap" type="user">
- <id property="id" column="id"/>
- <result property="userName" column="name"/>
- <result property="password" column="pass"/>
- </resultMap>
-
-
- <select id="selectUser" parameterType="int" resultMap="userResultMap" >
- select * from t_user where id = #{id}
- </select>
-
-
- <insert id="addUser" parameterType="user"
- useGeneratedKeys="true" keyProperty="id">
- insert into t_user(name,pass) values(#{userName},#{password})
- </insert>
-
-
- <update id="modifyUser" parameterType="user">
- update t_user set name=#{userName}, pass=#{password} where id=#{id}
- </update>
-
- <delete id="deleteUser" parameterType="int">
- delete from t_user where id=#{id}
- </delete>
-
- </mapper>
测试代码
- public class Test {
- static String resource = "mybatis-config.xml";
-
- public static void main(String[] args) throws IOException {
-
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sqlSessionFactory.openSession();
- try {
-
-
- User user = session.selectOne("user.selectUser", 1);
- System.out.println("user.getName()=" + user.getPassword());
-
- User addUser = new User();
- addUser.setUserName("NEWWWWW");
- addUser.setPassword("111111");
- session.insert("user.addUser", addUser);
-
-
- User modifyUser = new User();
- modifyUser.setUserName("NEWWWWW");
- modifyUser.setPassword("111111");
- modifyUser.setId(1);
-
-
- session.update("user.modifyUser", addUser);
-
-
- session.delete("user.deleteUser",2);
-
-
- session.commit();
-
-
- System.out.println("addUser.getId()" + addUser.getId() );
-
- } finally {
- session.close();
- }
- }
-
- }