码迷,mamicode.com
首页 > 其他好文 > 详细

myBatis 实现用户表增操作(复杂型)

时间:2015-11-12 11:42:30      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

增加

@Test
    public void addTest(){
        String resource = "mybatis-config.xml";
        SqlSession sqlSession = null;
        try {
            User user = new User();
            user.setUserCode("aaaa");
            user.setUserName("xxxx");
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = factory.openSession();
            sqlSession.insert("cn.bdqn.dao.UserMapper.add",user);
            sqlSession.commit();
        
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            sqlSession.close();
        }
        
    }

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>
</mapper>

在UserMapper.xml中的parameterType="cn.bdqn.pojo.User" 添加别名为User这样就方便些

<!-- 引入 jdbc.properties 文件-->
    <properties resource="jdbc.properties"/>
    <!-- alias别名 -->
    <typeAliases>
        <typeAlias type="cn.bdqn.pojo.User" alias="User"/>
    </typeAliases>

 

myBatis 实现用户表增操作(复杂型)

标签:

原文地址:http://www.cnblogs.com/xuerong/p/4958012.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!