myBatis 实现用户表增删查改操作<方法1 没有使用接口的>(最终版)

在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+id(方法名)的名字就可以访问 -->
<mapper namespace="cn.bdqn.dao.UserMapper">
    <!-- id要唯一的,一般是下拉类的方法名 -->
    <!-- 返回的是什么类型int -->
    <select id="count" resultType="int">
        select count(1) from user
    </select>
    <!-- 增加 -->
    <insert id="add" parameterType="User">
        insert into user(userCode,userName,userPassword)
            values (#{userCode},#{userName},#{userPassword})
    </insert>
    <!-- 修改 -->
    <update id="update" parameterType="User">
        update user set userCode=#{userCode},userName=#{userName},
        userPassword=#{userPassword} where id=#{id}
    </update>
    <!-- 删除 -->
    <delete id="delete" parameterType="User">
        delete from user where id=#{id}
    </delete>
    <!-- 查询 -->
    <select id="getUserList" resultType="User">
        select * from user
    </select>
</mapper>

同时加上mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<!-- 通过这个配置文件完成mybatis与数据库的连接 -->
<configuration>
    <!-- 引入 jdbc.properties 文件-->
    <properties resource="jdbc.properties"/>
    <!-- alias别名 -->
    <typeAliases>
        <!-- <typeAlias type="cn.bdqn.pojo.User" alias="User"/> -->
        <!-- 用这个比较方便,不用一个一个写。包下的就是他的类名 -->
        <package name="cn.bdqn.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <!--配置事务管理,采用JDBC的事务管理  -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED:mybatis自带的数据源,JNDI:基于tomcat的数据源 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <!-- 将mapper文件加入到配置文件中  将来mapper文件很多所以是mappers -->
    <mappers>
        <mapper resource="cn/bdqn/dao/UserMapper.xml"/>
    </mappers>
</configuration>

 

首先把相同的代码块拿出来封装成一个类MyBatisUtil

public class MyBatisUtil {
    private static SqlSessionFactory factory;
    
    /**
     * 一般情况下,如果有些代码必须在项目启动的时候就执行的时候,需要使用静态代码块,这种代码是主动执行的;
     * 需要在项目启动的时候就初始化,在不创建对象的情况下,其他程序来调用的时候,需要使用静态方法,这种代码是被动执行的.
     * 静态方法在类加载的时候 就已经加载 可以用类名直接调用
     */
    
    static{//在静态代码块下,factory只会被创建一次
        System.out.println("static factory===============");
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
    //创建sqlSession
    public static SqlSession createSqlSession(){
        return factory.openSession();
    }
    //关闭资源
    public static void closeSqlSession(SqlSession sqlSession){
        if(null != sqlSession) 
                sqlSession.close();
    }
}

接下来实现增删改查就很简单了----->注意:(增删改一定要记住在后面加commit())

public class UserDaoTest {
    private Logger logger = Logger.getLogger(UserDaoTest.class);
    //count
    @Test
    public void countTest() {
        SqlSession sqlSession = null;
        int count = 0;
        try {
            sqlSession = MyBatisUtil.createSqlSession();
            count = sqlSession.selectOne("cn.bdqn.dao.UserMapper.count");
            logger.debug("count==="+count);
        } catch (Exception e) {
            // TODO: handle exception
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
    
    //add
    @Test
    public void addTest(){
        SqlSession sqlSession = null;
        try {
            User user = new User();
            user.setUserCode("aaaa");
            user.setUserName("bbbbb");
            sqlSession = MyBatisUtil.createSqlSession();
            sqlSession.insert("cn.bdqn.dao.UserMapper.add",user);
            sqlSession.commit();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
    //修改
    @Test
    public void updateTest(){
        SqlSession sqlSession = null;
        try {
            User user = new User();
            user.setId(12);
            user.setUserCode("改1111");
            user.setUserName("改2222");
            sqlSession = MyBatisUtil.createSqlSession();
            sqlSession.update("cn.bdqn.dao.UserMapper.update",user);
            sqlSession.commit();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
    //删除
    @Test
    public void deleteTest(){
        SqlSession sqlSession = null;
        try {
            User user = new User();
            user.setId(12);
            sqlSession = MyBatisUtil.createSqlSession();
            sqlSession.delete("cn.bdqn.dao.UserMapper.delete",user);
            sqlSession.commit();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
}

 

//查询
    @Test
    public void getUserListTest(){
        SqlSession sqlSession = null;
        try {
            List<User> userList = new ArrayList<User>();
            sqlSession = MyBatisUtil.createSqlSession();
            userList = sqlSession.selectList("cn.bdqn.dao.UserMapper.getUserList");
            for(User user:userList){
                logger.debug("user的id==="+user.getId());
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

 

posted @ 2015-11-12 11:31  夏末、初秋  阅读(326)  评论(0编辑  收藏  举报