1. 程式人生 > >mybatis插入資料時返回主鍵(mysql資料庫)

mybatis插入資料時返回主鍵(mysql資料庫)

第一種方式使用useGeneratedKeys屬性

User類

public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
	...

mapper檔案

<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into user(username, birthday, sex, address)
        values (#{username}, #{birthday}, #{sex}, #{address})
    </insert>
  • 在insert標籤中需要將useGeneratedKeys屬性設定為true
  • keyProperty屬性值是主鍵對應的pojo中的屬性
  • 返回的主鍵會放置在入參物件中的id屬性上

mapper介面

public interface UserMapper {
    void insertUser(User user) throws Exception;
}

測試程式碼

@Test
    public void testInserUser () throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("張三");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("武漢");
        userMapper.insertUser(user);
        sqlSession.commit();
        System.out.println(user.getId());
        sqlSession.close();
    }

上面的測試程式碼中入參是一個user物件,返回的主鍵是在該物件的id屬性中,所以使用user.getId()可以獲取到該主鍵。

第二種方式selectKey標籤

mapper配置檔案

<insert id="insertUser" parameterType="test.User">
    <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>
  • keyProperty屬性值也是返回的主鍵值是與物件中的哪一個引數對應
  • resultType是返回的主鍵型別
  • select LAST_INSERT_ID()是mysql中的一個函式,用於自動返回下一個主鍵
  • order屬性,可以被設定為 BEFORE 或 AFTER。如果設定為 BEFORE,那麼它會首先選擇主鍵,設定 keyProperty 然後執行插入語句。如果設定為 AFTER,那麼先執行插入語句,然後是 selectKey 元素-這和如 Oracle 資料庫相似,可以在插入語句中嵌