zoukankan      html  css  js  c++  java
  • 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值。
  • 相关阅读:
    桌面右击新建没有记事本以解决?
    mysql int(3)与int(11)的区别
    PHPCMS 权限
    PHP 全局函数
    SESSION 丢失
    成功配置gVim的ZenCoding插件
    phpcms 模版源码分析
    更新首页
    隐藏apache访问错误显示系统和版本信息
    nginx 编译安装
  • 原文地址:https://www.cnblogs.com/xieshuang/p/14239467.html
Copyright © 2011-2022 走看看