【发布时间】:2021-03-25 15:42:52
【问题描述】:
我使用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)
然后是一个spring boot类:
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 都是零,它不是自动增加的
【问题讨论】: