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值。
原文地址:https://www.cnblogs.com/xieshuang/p/14239467.html