首页 > 解决方案 > spring boot 和 mybatis 自动增加 id

问题描述

我使用spring boot和mybatis将记录插入h2数据库,也使用自动增加id。首先,我和图书馆:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

然后是域类:

@Repository
package com.example.demo.domain;
public class Customer {
    private int id;
    private String name;
// getter setter and 3 constructor...
}

然后是映射器:

package com.example.demo.mapper;

import ...;
import com.example.demo.domain.Customer;
@Service
public interface CustomerMapper {
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into Customer (name) values (#{name})")
    public int insert(Customer c);
    
    @Select("select * from Customer")
    public List<Customer> sel();
    
}

在类路径的根目录下还有一个 schema.sql 文件,其中包含一个 sql:

drop table if exists customer
create table customer (id int,name varchar)

然后是一个弹簧引导类:

package com.example.demo;

import com.example.demo.domain.Customer;
import com.example.demo.mapper.CustomerMapper;

@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class Demo2Application implements CommandLineRunner{

    public static void main(String[] args) {
        SpringApplication.run(Demo2Application.class, args);
    }

    @Autowired
    CustomerMapper customerMapper;
    @Override
    public void run(String... args) throws Exception {
        // TODO Auto-generated method stub
        customerMapper.insert(new Customer("john"));
        customerMapper.insert(new Customer("james"));
        List<Customer> cus = customerMapper.sel();
        System.out.println(cus.get(0).getId());
        System.out.println(cus.get(1).getId());
    }

}

控制台打印:

0
0

这意味着我插入了两个人,但他们的 id 都是零,它不是自动增加的

标签: springmybatis

解决方案


您可以通过以下方式更改 schema.sql:

drop table if exists customer;
create table customer
(
    id   int auto_increment primary key,
    name varchar
);

该解决方案应该有效。

PS并且域模型不应该由spring容器在以下代码中管理:

@Repository
package com.example.demo.domain;
public class Customer {
    private int id;
    private String name;
// getter setter and 3 constructor...
}

只需删除@Repository 注释


推荐阅读