mybatis入门(七)

 

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.

posted @ 2015-05-25 15:19  加肥猫咪  阅读(...)  评论(...编辑  收藏