1. 程式人生 > >71.mybatis 如何獲取插入的id【從零開始學Spring Boot】

71.mybatis 如何獲取插入的id【從零開始學Spring Boot】

在之前的文章已經講過spring boot整合mybatis了,但是忘記說一個很重要的知識點了,那就是獲取獲取主鍵id,這篇文章補充下,spring boot整合mybatis看之前文章:

       其實這個也很簡單,主要是使用@Options註解,核心程式碼如下:

@Insert("insert into Demo(name,password) values(#{name},#{password})")

@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id"

public long save(Demo name

);

Demo的程式碼:

/**

 *

 * @author Angel(QQ:412887952QQ交流群:193341332)

 * @version v.0.1

 * @date 2016729上午10:18:33

 */

public class Demo {

    private long id;

    private String name;

    private String password;

    //省略setter and getter …

}

@Options註解中的工作就比較有意思,我們在插入記錄時,一般是定義主鍵自增(auto_increment),但是在某些情況下,我們插入一條記錄後,還想得到這條記錄的自增主鍵ID,useGeneratedKeys=true就是定義資料庫返回主鍵ID的,常用的屬性如下:

useCache=true

flushCache=false

resultSetType=FORWARD_ONLY

statementType=PREPARED

fetchSize= -1,timeout=-1 ,

useGeneratedKeys=false 

keyProperty=”id“。