mybaits四-3:获取保存数据的id

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.atchina.dao.IUserDao">

    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.atchina.domain.User">
        <selectKey keyColumn="id" keyProperty="id" resultType="String" order="AFTER">
            select last_insert_id();
        </selectKey>

        insert into user(username, birthday, sex, address)
        values ( #{username}, #{birthday}, #{sex}, #{address})
    </insert>

    
</mapper>

 

package com.atchina.test;

import com.atchina.dao.IUserDao;
import com.atchina.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisTest {

    InputStream in = null;
    SqlSessionFactory sessionFactory = null;
    SqlSession sqlSession = null;
    IUserDao userDao = null;

    @Before
    public void init() throws Exception{
        in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        sessionFactory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = sessionFactory.openSession();
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    @Test
    public void testSave(){
        User u = new User();
        u.setUsername("天下");
        u.setBirthday(new Date());
        u.setSex("男");
        u.setAddress("梁山");

        System.out.println("保存之前:"+u);
        userDao.saveUser(u);
        System.out.println("保存之后:"+u);
    }


    @After
    public void destroy() throws Exception{
        // 提交
        sqlSession.commit();

        // 释放资源
        sqlSession.close();
        in.close();
    }
}

mybaits四-3:获取保存数据的id

上一篇:mybatis-plus解决 sqlserver批量插入list报错(转)


下一篇:org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.xxxxxxxx