添加用户信息
MyBatis全局配置文件、mysql数据库相关信息、映射文件User.xml等,都是基于这篇博客mybatis学习笔记(三):根据用户ID(主键)查询用户信息,有需要可以点击查看
在User.xml
中配置添加用户的statement
添加内容如下:
<insert id="insertUser" parameterType="com.trc.qa.po.User">
INSERT INTO user (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
insert>
//新增用户
@Test
public void insertUserTest() throws IOException {
//mybatis配置文件
String resource = "SqlMapConfig.xml";
//得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
//创建会话工厂,传入mybatis的配置文件信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//创建用户对象
User user = new User();
user.setUsername("王大锤");
user.setBirthday(new Date());
user.setSex("1");
user.setAddress("河南洛阳");
sqlSession.insert("test.insertUser", user);
//提交事务
sqlSession.commit();
//获取用户信息主键
System.out.println(user.getId());
sqlSession.close();
}
......
[DEBUG]14:55:55,088,main,[Class]JdbcTransaction, [Method]openConnection, Opening JDBC Connection
[DEBUG]14:55:55,373,main,[Class]PooledDataSource, [Method]popConnection, Created connection 1630521067.
[DEBUG]14:55:55,373,main,[Class]JdbcTransaction, [Method]setDesiredAutoCommit, Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@612fc6eb]
[DEBUG]14:55:55,376,main,[Class]insertUser, [Method]debug, ==> Preparing: INSERT INTO user (username,birthday,sex,address) VALUES(?,?,?,?)
[DEBUG]14:55:55,419,main,[Class]insertUser, [Method]debug, ==> Parameters: 王大锤(String), 2018-07-25 14:55:55.083(Timestamp), 1(String), 河南洛阳(String)
[DEBUG]14:55:55,423,main,[Class]insertUser, [Method]debug, <== Updates: 1
[DEBUG]14:55:55,425,main,[Class]insertUser!selectKey, [Method]debug, ==> Preparing: select last_insert_id()
[DEBUG]14:55:55,427,main,[Class]insertUser!selectKey, [Method]debug, ==> Parameters:
[DEBUG]14:55:55,455,main,[Class]insertUser!selectKey, [Method]debug, <== Total: 1
[DEBUG]14:55:55,455,main,[Class]JdbcTransaction, [Method]commit, Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@612fc6eb]
0
[DEBUG]14:55:55,456,main,[Class]JdbcTransaction, [Method]resetAutoCommit, Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@612fc6eb]
......
查看数据库相关数据,已经插入一条用户信息