spring - 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 都是零,它不是自动增加的
解决方案
您可以通过以下方式更改 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 注释
推荐阅读
- kdb - 在 KDB 中加载两个分区表时列值发生变化 (q)
- angular - 克隆离子项目后无法服务
- r - 在 R 中查找所选变量的平均值
- angular - Angular 将 html 属性(即样式/类)从父级传递给子级
- ubuntu - CALDB 的问题——更好的数据处理
- python - Django查询集过滤器基于孩子的数量
- javascript - 如何在地图上的google api中添加一个按钮
- stackexchange-api - 如何在 Stack Exchange API 中使用 fromdate 和 todate 参数?
- amazon-web-services - 特定天后使用 Lambda 排空 SQS 队列
- python - 我试图在线打印出标题的文字,但控制台上没有显示任何内容