MyBatis插入单条数据
<!-- 添加用户 --> <insert id="insertUser" parameterType="com.hl.myabtis.first.beas.User"> insert into user (username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address}) </insert>
主键自增长所以不用添加,字段名要与数据库字段名一致!
@Test public void testaddUser() throws Exception{ //创建会话工厂 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource ); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //通过工厂得到SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); User user = new User(); user.setAddress("秦时明月之惊弓之鸟"); user.setBirthday(new Date()); user.setSex('1'); user.setUsername("蒙恬"); //使用SqlSession操作数据库 sqlSession.insert("test.insertUser", user); //手动提交事务 sqlSession.commit(); //关闭资源 sqlSession.close(); }