mybatis 向數據庫插入數據時獲取其主鍵值(序列值)的實現小記

本文以oracle數據庫爲例,簡單說明(演示項目用的springboot+mybatis+oracle,只貼部分關鍵代碼):

分兩種情況:

01、在mapper接口傳參時,以java實體類傳參;

public interface UserMapper {
      int insertUser(@Param("user") User user);
}

02、在mapper接口傳參時,以map傳參;

public interface UserMapper {
      int insertUser(@Param("paramMap") Map<String, Object> paramMap);
}

首先第一種情況(01、在mapper接口傳參時,以java實體類傳參)

  首先創建一個User實體類:

public class User {
	private Integer id;
	private String name;
	
	set get...方法忽略
}
然後在xml中加如下代碼(暫不解釋代碼,在"02、"統一解釋):

<insert id="insertUser" parameterType="com.test.User" >
    <selectKey keyProperty="id" resultType="int" order="BEFORE" >
        select USER_SEQ.nextval from DUAL 
    </selectKey>
    insert into USER
    	(id, name)
    values
    	(#{id}, #{name})
</insert>
在業務層的代碼如下:
User user = new User();
user.setName("zhangsan");
//向用戶表中新加一個用戶,返回數據庫受影響的行數
int count = userMapper.insertUser(user);
//獲取新用戶的主鍵id值,並打印到控制檯
System.out.print(user.getId());

其次第二種情況下(02、在mapper接口傳參時,以map傳參)

首先在xml中加如下代碼:

<insert id="insertUser" parameterType="hashMap" >
    <selectKey keyProperty="paramMap.id" resultType="int" order="BEFORE" >
        select USER_SEQ.nextval from DUAL 
    </selectKey>
    insert into USER
    	(ID, NAME)
    values
    	(#{paramMap.id}, #{paramMap.name})
</insert>

對上面代碼簡單解釋一下:order = "BEFORE" 代表在執行insert語句之前先執行selectKey中的語句,這時我們先獲取了User表的序列的下一個值,keyProperty="paramMap.id" 就是將獲取到的序列值賦值給paramMap中的id,這時再執行insert語句的時候#{paramMap.id} 就已經是獲取到的序列值了,這樣我們在程序中也就獲取到了新插入數據的id值,關鍵代碼在下面貼上;

然後在代碼裏面(service層或者controller層),調用dao層時添加如下代碼(只貼關鍵代碼)

@Autowired
private UserMapper userMapper;
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("id", null);
paramMap.put("name","zhangsan");
//向用戶表中新加一個用戶,返回數據庫受影響的行數
int count = userMapper.insertUser(paramMap);
//獲取新用戶的主鍵id值,並打印到控制檯
System.out.print(paramMap.get("id").toString());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章