03_插入数据

【工程如01】

【user.xml】

  <!-- 
         添加用户
         parameterType:指定输入参数类型是pojo(包括用户信息)
         #{}中指定pojo的属性名:接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值
      -->
     <insert id="insertUser" parameterType="com.Higgin.Mybatis.po.User">
         insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
     </insert>
<!-- 添加用户并返回插入数据的ID      -->
     <insert id="insertUserReturnId" parameterType="com.Higgin.Mybatis.po.User">
         <!-- 
             将插入数据的主键返回,返回到user对象中 
             SELECT LAST_INSERT_ID():得到刚刚insert进去记录的主键值,只适用于自增主键
             keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
             order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行熟悉
             resultType:指定SELECT LAST_INSERT_ID()的结果类型
         -->
         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
             SELECT LAST_INSERT_ID()
         </selectKey>
         insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
     </insert>

【MyBatisTest.java】

@Test
    public void testInsertUser() throws IOException{
        //mybatis映射文件
        String resource="sqlMapConfig.xml";
        //得到mybatis映射文件
        InputStream inputStream=Resources.getResourceAsStream(resource);
        //创建会话,传递mybatis配置信息
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
        //通过工厂得到session
        SqlSession sqlSession=sqlSessionFactory.openSession();
        
        User user=new User();
        user.setUsername("王大明2");
        user.setSex("0");
        user.setAddress("深圳");
        user.setBirthday(new Date());
        //插入数据后返回id到user对象中
        sqlSession.insert("test.insertUserReturnId",user);
        
     system.out.println("新插入的id=="+user.getId());
//提交事务 sqlSession.commit(); //这句必须要有,不然插不进去数据 //关闭会话 sqlSession.close(); }

【运行结果】

另外一个方式类似,不演示

原文地址:https://www.cnblogs.com/HigginCui/p/5699766.html