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

mybatis入门(七)

时间:2015-05-25 16:16:03      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

 

mybatis入门--添加一个用户

//添加用户
    @Test
    public void insertUserTest() throws IOException {
        // 通过工厂得到SqlSession
        SqlSession sqlSession = null;
        try {
            // mybatis配置文件
            String resource = "SqlMapConfig.xml";
            // 得到配置文件流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 创建会话工厂,传入mybatis的配置文件信息
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
            User user=new User();
            user.setUsername("王小明");
            user.setAddress("福建福州");
            user.setBirthday(new Date());
            user.setSex("2");
            sqlSession.insert("test.insertUser", user);
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                // 释放资源
                sqlSession.close();
            }

        }
    }

User.xml

<!-- 添加用户 
    parameterType:指定输入 参数类型是pojo(包括 用户信息)
    #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
    -->
    <insert id="insertUser" parameterType="ql.mybatis.pojo.User">
        insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
    </insert>

 

 

日志:

DEBUG [main] - Logging initialized using ‘class org.apache.ibatis.logging.slf4j.Slf4jImpl‘ adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 67418210.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@404b862]
DEBUG [main] - ==>  Preparing: insert into user(username,birthday,sex,address) value(?,?,?,?)
DEBUG [main] - ==> Parameters: 王小明(String), 2015-05-25 15:16:20.611(Timestamp), 2(String), 福建福州(String)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@404b862]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@404b862]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@404b862]
DEBUG [main] - Returned connection 67418210 to pool.

mybatis入门(七)

标签:

原文地址:http://www.cnblogs.com/ql211lin/p/4527940.html

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