Fork me on GitHub

MyBatis的CRUD操作

接上篇,下面演示对users表的其他常见操作。

因为像加载mybatis的配置文件、构建sqlSession的工厂这些操作都是重复的,我们可以写一个工具类来方便我们操作

package com.lhs.util;

import java.io.InputStream;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class MybatisUtils {

    public static SqlSessionFactory getFactory() {
        String resource = "mybatis-config.xml";
        InputStream is = MybatisUtils.class.getClassLoader().getResourceAsStream(
                resource);

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

        return factory;
    }
}

一、添加一个用户

 在userMapper.xml中写入要映射的sql语句

<!-- 添加user -->
<insert id="addUser" parameterType="com.lhs.model.User">
	insert into users(name,age) values(#{name},#{age})
</insert>

  写测试方法:

    @Test
    public void testAdd() 
    {
        SqlSessionFactory factory = new MybatisUtils().getFactory();
        SqlSession sqlSession = factory.openSession();
        
        String statement = "com.lhs.model.userMapper.addUser";
        User u = new User();
        u.setName("hello");
        u.setAge(22);
        int insert = sqlSession.insert(statement, u);
        
        sqlSession.commit();//提交事务
        System.out.println(insert);
    }

最后打印出1,说明影响了一行,插入成功!

二、根据id删除一条记录

  在userMapper.xml中写入要映射的sql语句

<!-- 删除user -->
<delete id="deleteUser" parameterType="int">
    delete from users where id=#{id}
</delete>

写测试方法:

@Test
    public void testDelete() 
    {
        SqlSessionFactory factory = new MybatisUtils().getFactory();
        SqlSession sqlSession = factory.openSession();
        
        String statement = "com.lhs.model.userMapper.deleteUser";

        int delete = sqlSession.insert(statement,3);
        
        sqlSession.commit();//提交事务
        System.out.println(delete);
    }

最后打印出1,删除成功!

 三、更新用户

  在users表中添加要映射的sql语句

<!-- 更新user -->
<update id="updateUser" parameterType="com.lhs.model.User">
        update users set name=#{name},age=#{age} where id=#{id}
</update>

写测试方法:

@Test
    public void testUpdate() 
    {
        SqlSessionFactory factory = new MybatisUtils().getFactory();
        SqlSession sqlSession = factory.openSession();
        
        String statement = "com.lhs.model.userMapper.updateUser";
        
        User u = new User();
        u.setId(2);
        u.setName("lhs");
        u.setAge(22);

        int update = sqlSession.update(statement, u);
        
        sqlSession.commit();//提交事务
        System.out.println(update);
    }

最后打出1,更新成功!

 

posted @ 2014-08-11 00:16  龙族小龙  阅读(234)  评论(0编辑  收藏  举报