Sequence
-
定义IKeyGenerator的实现
@Configuration
public class MybatisPlusConfig {
@Bean
public IKeyGenerator keyGenerator() {
return new DB2KeyGenerator();
}
}
- 配置KeySequence注解
@Data
@KeySequence("SEQ_USER")
public class User {
@TableId(value = "id", type = IdType.INPUT)
private Long id;
private String name;
private Integer age;
private String email;
}
- 测试
@SpringBootTest
public class SequenceTest {
@Resource
UserMapper userMapper;
/**
* INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
* 1000(Long), sequence(String), 18(Integer), test@baomidou.com(String)
*
* INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
* 1001(Long), sequence2(String), 19(Integer), test2@baomidou.com(String)
*/
@Test
public void testInsert() {
User user = new User();
user.setAge(18);
user.setEmail("test@baomidou.com");
user.setName("sequence");
userMapper.insert(user);
Long id1 = user.getId();
System.out.println(id1);
Assertions.assertTrue(id1 >= 1000, "sequence start with 1000");
user = new User();
user.setAge(19);
user.setEmail("test2@baomidou.com");
user.setName("sequence2");
userMapper.insert(user);
Long id2 = user.getId();
Assertions.assertTrue(id2 - id1 == 1, "squence increment by 1");
}
}