1. 程式人生 > 其它 >mybatis插入時獲取自增主鍵

mybatis插入時獲取自增主鍵

技術標籤:雜七雜八mybatis

一、自增主鍵優缺點

1.優點

  • 查詢和插入的效能較高(增量增長,按序存放,具體可檢視InnoDB相關資料瞭解B+樹)
  • 插入新記錄時不用擔心主鍵會重複

2.缺點

  • 分散式系統中不太適用

二、回到正文

1.核心jar包

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.3</version>
    </dependency>
    
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper</artifactId>
        <version>3.3.9</version>
    </dependency>

2.配置mybatis掃描路徑

@SpringBootApplication
@MapperScan(basePackages = {"com.xsh.springdemo"})
public class SpringdemoApplication {
public static void main(String[] args) {
    SpringApplication.run(SpringdemoApplication.class, args);
}

3.編寫mapper檔案
這裡我沒有使用xml形式,直接才用註解形式更方便簡潔

public interface UserMapper extends Mapper<UserModel> {
    @Insert("insert into test_user (name, address)value(#{user.name},#{user.address})")
    @Options(useGeneratedKeys = true, keyProperty = "user.id", keyColumn = "id")
    int addUser(@Param("user") UserModel user);
}

其中UserModel內容

@Data
public class UserModel implements Serializable {

    private Integer id;
    private String name;
    private String address;

    public UserModel(String name, String address) {
        this.name=name;
        this.address=address;
    }
}

test_user表DDL

CREATE TABLE `test_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

4.編寫單元測試用例

 @Autowired
private UserMapper userMapper;
@Test
public void testAdd(){
    UserModel userModel = new UserModel("測試姓名","測試地址");
    userMapper.addUser(userModel);
    System.out.println("主鍵為:"+userModel.getId());
}

在這裡插入圖片描述

呼叫實體的`getId`方法即可獲取都記錄的id值。