19 Commits

Author SHA1 Message Date
杨黄林
0c737b5449 版本号更新为1.13.1 2026-02-28 14:05:57 +08:00
杨黄林
9a018b6af9 修复达梦数据库下自动创建表时不会自动变更更新时间问题 2026-02-28 14:03:58 +08:00
杨黄林
64724de96c 修复pgsql自动创建sql失败问题 2026-01-14 17:45:36 +08:00
杨黄林
8321032918 去掉GBase8c,这个没自己的连接,它的连接是pgsql 2026-01-14 16:42:19 +08:00
杨黄林
28b95468a3 版本号升级到1.13.0 2026-01-14 14:01:34 +08:00
杨黄林
828a7395d2 增加南大通用GBase8c 2026-01-14 14:01:19 +08:00
20ddc4412e 精简代码 2025-06-05 13:17:38 +08:00
c65bd7b36f 代码优化 2025-06-05 12:59:32 +08:00
721cd48d96 支持达梦数据库V8 2025-06-05 12:58:18 +08:00
e2e5939810 新增 支持达梦数据库
新增 Sequences 增加 updateTime
新增 增加查询序号是否锁定的方法 locked
新增 增加将序号设为未使用的方法 unused
新增 增加 SequencesUnlock find(SequencesUnlock sequencesUnlock) 和 SequencesUnused find(SequencesUnused sequencesUnused)
2025-01-15 11:42:46 +08:00
670cd52c40 新增 支持pgsql、kingbasees、mysql三种数据库 2024-05-30 10:39:09 +08:00
杨黄林
9104af2923 调整 增加固定字符串占位符
调整 解析序列号时,增加根据固定字符串长度解析 Sequences parse(String formatted, String pattern, Integer fixLength);
2023-05-08 17:48:37 +08:00
杨黄林
9f7baadf7a 修复 注释问题 2023-05-08 16:10:33 +08:00
杨黄林
32d3de7550 Merge remote-tracking branch 'gitea/master'
# Conflicts:
#	README.md
2022-11-30 15:24:14 +08:00
杨黄林
bb2ddfc34a 新增 格式化时,可以传入年、月、日 2022-11-30 14:48:18 +08:00
3615ed9eec 更新 'README.md' 2022-07-09 09:55:55 +08:00
53ac87f0e8 更新 'README.md' 2022-07-09 09:42:22 +08:00
6dc6498e6c generate方法增加无序号参数withOutSeq;基础配置中可以配置年、月不足2位时是否补零 2022-07-09 09:35:59 +08:00
yhl452493373
4cbf9d72d3 增加lock(Sequences sequences, boolean ignoreSeq)、release(Sequences sequences, boolean ignoreSeq)方法 2022-02-21 16:03:41 +08:00
30 changed files with 1194 additions and 406 deletions

263
README.md
View File

@@ -4,11 +4,15 @@
用于生成全局自增序号,跳过的序号可以回收使用。
***本生成器内部使用transactionTemplate进行事务管理如果你项目中给使用此生成器的方法或类加了`@Transactional`
注解则需将新建一个Service来专门负责调用此生成器的方法同时要给新建的类增加`@Transactional`
注解,并设置`propagation = Propagation.NOT_SUPPORTED`***
---
使用方法:
+ 在项目中放置jar包的地方把seq-1.6.2.jar、seq-1.6.2-sources.jar、seq-1.6.2-pom.xml复制过去
+ 在项目中放置jar包的地方把seq-1.9.2.jar、seq-1.9.2-sources.jar、seq-1.9.2-pom.xml复制过去
+ 在pom.xml中增加以下内容然后执行maven命令mvn clean
```xml
@@ -18,7 +22,7 @@
<dependency>
<groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId>
<version>1.6.2</version>
<version>1.9.2</version>
<exclusions>
<!-- 如若你项目中有引用spring-jdbc则需要排除seq的jdbc依赖 -->
<exclusion>
@@ -50,13 +54,13 @@
</goals>
<configuration>
<!-- ${project.basedir}表示当前项目的根目录 -->
<file>${project.basedir}/lib/seq-1.6.2.jar</file>
<pomFile>${project.basedir}/lib/seq-1.6.2-pom.xml</pomFile>
<sources>${project.basedir}/lib/seq-1.6.2-sources.jar</sources>
<file>${project.basedir}/lib/seq-1.9.2.jar</file>
<pomFile>${project.basedir}/lib/seq-1.9.2-pom.xml</pomFile>
<sources>${project.basedir}/lib/seq-1.9.2-sources.jar</sources>
<repositoryLayout>default</repositoryLayout>
<groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId>
<version>1.6.2</version>
<version>1.9.2</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
@@ -68,78 +72,7 @@
</project>
```
+ springboot中配置方式一(优先):直接注入已有jdbcTemplate和transactionTemplate
```java
package com.yanghuanglin.springseq.baseConfig;
import com.yanghuanglin.seq.baseConfig.GeneratorConfig;
import com.yanghuanglin.seq.baseConfig.TableConfig;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.generator.impl.SequencesGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Resource;
/**
* 基于已有的jdbcTemplate和transactionTemplate一般如果引用了spring的数据库操作如jpa、mybatis都可以直接注入
*/
@Configuration
public class SeqGeneratorConfig {
/**
* 注入已有的数据库操作模板
*/
@Resource
private JdbcTemplate jdbcTemplate;
/**
* 注入已有的事务操作模板
*/
@Resource
private TransactionTemplate transactionTemplate;
/**
* 序号表配置类
*/
@Bean
public TableConfig tableConfig() {
TableConfig tableConfig = new TableConfig();
//自定义表名、字段名
tableConfig.setTable("sequences");
tableConfig.setKeyColumn("SEQUENCE_KEY");
tableConfig.setTypeColumn("SEQUENCE_TYPE");
tableConfig.setSeqColumn("NEXT_ID");
tableConfig.setCreateTimeColumn("CREATE_TIME");
return tableConfig;
}
/**
* 序号生成器配置类
* @param tableConfig 序号表配置类
*/
@Bean
public GeneratorConfig generatorConfig(TableConfig tableConfig) {
GeneratorConfig generatorConfig = new GeneratorConfig();
generatorConfig.setJdbcTemplate(jdbcTemplate);
generatorConfig.setTransactionTemplate(transactionTemplate);
generatorConfig.setTableConfig(tableConfig);
return generatorConfig;
}
/**
* 注册序号生成器类
* @param generatorConfig 序号生成器配置类
*/
@Bean
public Generator generator(GeneratorConfig generatorConfig) {
return new SequencesGenerator(generatorConfig);
}
}
```
+ springboot中配置方式二注入已有的dataSource或自行构建dataSource通过dataSource自动生成jdbcTemplate和transactionTemplate
+ springboot中配置方式注入已有的dataSource或自行构建dataSource通过dataSource自动生成jdbcTemplate和transactionTemplate
```java
package com.yanghuanglin.springseq.baseConfig;
@@ -160,7 +93,7 @@ import javax.sql.DataSource;
@Configuration
public class SeqGeneratorConfig {
/**
* 注入已有的数据源,果没有,也可以自行构建
* 注入已有的数据源,果没有,也可以自行构建
*/
@Resource
private DataSource dataSource;
@@ -273,20 +206,16 @@ TableConfig配置项通过set方法设置一般不用改如果已有相
GeneratorConfig配置项通过set方法设置
| 配置项 | 类型 | 默认值 | 说明 |
|---------------------|------------------------------------------------------------------|------------------|------------------|
| dataSource | javax.sql.DataSource | null | 数据源 |
| jdbcTemplate | org.springframework.jdbc.core.JdbcTemplate | null | 数据库操作模板 |
| transactionTemplate | org.springframework.jdbc.core.JdbcTemplate | null | 事务操作模板 |
| transactionManager | org.springframework.jdbc.datasource.DataSourceTransactionManager | null | 事务管理器 |
| autoCreate | Boolean | true | 开启自动建表 |
| step | Integer | 1 | 序号增加时的步长 |
| type | String | DEFAULT | 默认序号类型 |
| minLength | Integer | 1 | 默认序号格式化后长度,不足的补零 |
| tableConfig | com.yanghuanglin.seq.baseConfig.TableConfig | TableConfig的默认配置 | 表配置 |
以上配置中jdbcTemplate和transactionTemplate优先级最高如果jdbcTemplate、transactionTemplate、dataSource、transactionManager同时配置则dataSource和transactionManager无效
可进行这几种组合dataSource+autoCreate+step+minLength+tableConfigjdbcTemplate+transactionTemplate+autoCreate+step+minLength+tableConfigjdbcTemplate+transactionManager+autoCreate+step+minLength+tableConfig
| 配置项 | 类型 | 默认值 | 说明 |
|------------------|---------------------------------------------|------------------|------------------|
| dataSource | javax.sql.DataSource | null | 数据源 |
| monthZeroFilling | Boolean | true | 月份不足2位时自动补零 |
| dayZeroFilling | Boolean | true | 当前日期不足2位时自动补零 |
| autoCreate | Boolean | true | 开启自动建表 |
| step | Integer | 1 | 序号增加时的步长 |
| type | String | DEFAULT | 默认序号类型 |
| minLength | Integer | 1 | 默认序号格式化后长度,不足的补零 |
| tableConfig | com.yanghuanglin.seq.baseConfig.TableConfig | TableConfig的默认配置 | 表配置 |
---
Generator方法如下
@@ -304,6 +233,14 @@ import com.yanghuanglin.seq.po.SequencesUnused;
import java.util.Date;
public interface Generator {
/**
* 判断格式定义中是否有序号
*
* @param pattern 格式
* @return 是否包含序号
*/
boolean containSeq(String pattern);
/**
* 根据传入的key和type生成可用的序号对象。
* <p/>
@@ -312,9 +249,15 @@ public interface Generator {
* 如果根据key和默认的{@link GeneratorConfig#getType()}在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @param key 数据字典中的编码
* @param withOutSeq 序号对象不包含序号,其值通过{@link #containSeq(String)}来判断
* @return 可用的序号对象
*/
Sequences generate(String key, Boolean withOutSeq);
/**
* 同 {@link #generate(String, Boolean)}第二个参数默认为false
*/
Sequences generate(String key);
/**
@@ -325,28 +268,40 @@ public interface Generator {
* 如果根据key和type在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @param type 序号类型
* @param key 数据字典中的编码
* @param type 序号类型
* @param withOutSeq 序号对象不包含序号,其值通过{@link #containSeq(String)}来判断
* @return 可用的序号对象
*/
Sequences generate(String key, String type, Boolean withOutSeq);
/**
* 同{@link #generate(String, String, Boolean)}第三个参数默认为false
*/
Sequences generate(String key, String type);
/**
* 返回根据{@link #generate(String, String)}得到的序号对象,补零后的序号字符串
* 返回根据{@link #generate(String, String, Boolean)}得到的序号对象,补零后的序号字符串
* <p/>
* 如生成的为3而minLength为5则返回的是00003
*
* @param key 数据字典中的编码
* @param type 序号类型
* @param minLength 序号数字最小长度
* @param key 数据字典中的编码
* @param type 序号类型
* @param minLength 序号数字最小长度
* @param withOutSeq 序号对象不包含序号,其值通过{@link #containSeq(String)}来判断
* @return 补零后的字符串
*/
String generate(String key, String type, Integer minLength, Boolean withOutSeq);
/**
* 同{@link #generate(String, String, Integer, Boolean)}第四个参数默认为false
*/
String generate(String key, String type, Integer minLength);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param pattern 格式
@@ -355,9 +310,9 @@ public interface Generator {
String format(Sequences sequences, String pattern);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param minLength 序号数字最小长度
@@ -369,7 +324,7 @@ public interface Generator {
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR#getPlaceholder()}(当前年份)、{@link FormatPlaceholder#MONTH#getPlaceholder()}(当前月份)、{@link FormatPlaceholder#DAY#getPlaceholder()}(当前日期)、{@link FormatPlaceholder#SEQ#getPlaceholder()}(生成的字符串序号)四个变量
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下
* <p/>
@@ -384,7 +339,7 @@ public interface Generator {
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/>
@@ -400,44 +355,64 @@ public interface Generator {
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param fix 序号中的固定字符串
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, String pattern);
String format(Long seq, String fix, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param fix 序号中的固定字符串
* @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, Integer minLength, String pattern);
String format(Long seq, String fix, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param fix 序号中的固定字符串
* @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式
* @param year 格式化时使用的年
* @param month 格式化时使用的月
* @param day 格式化时使用的日
* @return 格式化后的序号字符串
*/
String format(Long seq, String fix, Integer minLength, String pattern, Integer year, Integer month, Integer day);
/**
* 将已格式化的序号解析为序号对象
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}可能有值
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}可能有值
* <p/>
* 如果生成序号时序号的key在年、月、日上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}进行组合进而得到key
* 如果生成序号时序号的key在年、月、日上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}进行组合进而得到key
* <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/>
@@ -449,10 +424,30 @@ public interface Generator {
*/
Sequences parse(String formatted, String pattern);
/**
* 将已格式化的序号解析为序号对象
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}可能有值
* <p/>
* 如果生成序号时序号的key在年、月、日上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}进行组合进而得到key
* <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/>
* 注意:序号格式和格式化后的字符串占位一定要匹配。如:处〔#year##month#10801第#seq#号 对应 处20220210801第10001号而不能对应 处2022021110801第10001号
*
* @param formatted 格式化后的序号字符串
* @param pattern 序号格式
* @param fixLength 序号中的固定字符串的长度
* @return 包含了序号字符串对应年如果有、月如果有、日如果有、固定字符串如果有、序号的序号对象其key需要根据情况手动设置type为{@link GeneratorConfig#getType()}的默认值
*/
Sequences parse(String formatted, String pattern, Integer fixLength);
/**
* 锁定指定序号,在序号生成后,调用该序号的逻辑完成后需要执行此方法
* <p/>
* 如办理案件时,先调用{@link #generate(String, String)}或者{@link #generate(String, String, Integer)}生成了序号,之后对案件进行了入库,如果入库完毕,则将该序号锁定,说明这个序号已被使用
* 如办理案件时,先调用{@link #generate(String, String, Boolean)}或者{@link #generate(String, String, Integer, Boolean)}生成了序号,之后对案件进行了入库,如果入库完毕,则将该序号锁定,说明这个序号已被使用
* <p/>
* 注意,此处的锁定非数据库中锁定,而是{@link SequencesUnused}和{@link SequencesUnlock}中均不存在key、type、seq相同的记录视为锁定。因此此处实际是把这两个表中的记录均删除了
*
@@ -461,12 +456,23 @@ public interface Generator {
*/
boolean lock(Sequences sequences);
/**
* 忽略{@link Sequences#getSeq()} ,仅通过{@link Sequences#getKey()}和{@link Sequences#getType()}来锁定序号。
* <p/>
* 如果ignoreSeq为false则等价于{@link #lock(Sequences)}
*
* @param sequences 需要锁定的序号
* @param ignoreSeq 是否忽略序号
* @return 锁定结果
*/
boolean lock(Sequences sequences, boolean ignoreSeq);
/**
* 释放所有未使用的序号
* <p/>
* {@link SequencesUnlock}中未通过{@link #lock(Sequences)}方法锁定的序号会一直存在,调用此方法会将里面的所有序号都移动到{@link SequencesUnused}中,下次生成序号时优先从{@link SequencesUnused}获取。
*/
void release();
boolean release();
/**
* 释放指定时间段内未使用的序号
@@ -476,7 +482,7 @@ public interface Generator {
* @param begin 开始时间
* @param end 结束时间
*/
void release(Date begin, Date end);
boolean release(Date begin, Date end);
/**
* 释放从开始时间开始,到现在时间之间未使用的序号。结束时间为方法执行时的时间
@@ -497,17 +503,27 @@ public interface Generator {
*
* @param sequences 需要释放的序号。一般是一个通过{@link Sequences#setKey(String)}、{@link Sequences#setType(String)}、{@link Sequences#setSeq(Long)}三方法一起手动构建或通过{@link Sequences#Sequences(String, String, Long)}构造方法构建的实例对象
*/
void release(Sequences sequences);
boolean release(Sequences sequences);
/**
* 忽略{@link Sequences#getSeq()}来释放指定序号。一般用于业务对象删除后,对应序号需要回收使用时。
* <p/>
* 如果ignoreSeq为false则等价于{@link #release(Sequences)}
*
* @param sequences 需要释放的序号。一般是一个通过{@link Sequences#setKey(String)}、{@link Sequences#setType(String)}、{@link Sequences#setSeq(Long)}三方法一起手动构建或通过{@link Sequences#Sequences(String, String, Long)}构造方法构建的实例对象
* @param ignoreSeq 是否忽略序号
*/
boolean release(Sequences sequences, boolean ignoreSeq);
/**
* 清空所有闲置序号和未锁定序号
*/
void clear();
boolean clear();
/**
* 清空指定时间段内闲置序号和未锁定序号
*/
void clear(Date begin, Date end);
boolean clear(Date begin, Date end);
/**
* 清空从开始时间到限制时间之间闲置序号和未锁定序号,结束时间为方法执行时的时间
@@ -523,5 +539,4 @@ public interface Generator {
*/
void clearBefore(Date end);
}
```

36
pom.xml
View File

@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId>
<version>1.6.2</version>
<version>1.13.1</version>
<name>seq</name>
<description>seq</description>
<properties>
@@ -14,12 +14,31 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.15</version>
<version>5.3.36</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
<version>8.0.33</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.com.kingbase</groupId>
<artifactId>kingbase8</artifactId>
<version>8.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.dameng</groupId>
<artifactId>DmJdbcDriver18</artifactId>
<version>8.1.3.140</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
@@ -30,6 +49,16 @@
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>rebel.xml</exclude>
<exclude>rebel-remote.xml</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -40,6 +69,7 @@
<target>8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>

View File

@@ -6,6 +6,7 @@ import com.yanghuanglin.seq.dao.SequencesUnusedDao;
import com.yanghuanglin.seq.dao.impl.SequencesDaoImpl;
import com.yanghuanglin.seq.dao.impl.SequencesUnlockDaoImpl;
import com.yanghuanglin.seq.dao.impl.SequencesUnusedDaoImpl;
import com.yanghuanglin.seq.enums.DbType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
@@ -28,6 +29,9 @@ public class BaseConfig {
private Integer step;
private String type;
private Integer minLength;
private Boolean monthZeroFilling;
private Boolean dayZeroFilling;
private DbType dbType;
private BaseConfig() {
}
@@ -48,10 +52,10 @@ public class BaseConfig {
synchronized (BaseConfig.class) {
if (instance == null) {
instance = new BaseConfig();
instance.init(generatorConfig);
}
}
}
instance.init(generatorConfig);
return instance;
}
@@ -125,46 +129,48 @@ public class BaseConfig {
return minLength;
}
public Boolean getMonthZeroFilling() {
if (monthZeroFilling == null)
throw new NullPointerException("请先初始化BaseConfig");
return monthZeroFilling;
}
public void setMonthZeroFilling(Boolean monthZeroFilling) {
this.monthZeroFilling = monthZeroFilling;
}
public Boolean getDayZeroFilling() {
if (dayZeroFilling == null)
throw new NullPointerException("请先初始化BaseConfig");
return dayZeroFilling;
}
public void setDayZeroFilling(Boolean dayZeroFilling) {
this.dayZeroFilling = dayZeroFilling;
}
public void setMinLength(Integer minLength) {
this.minLength = minLength;
}
private void init(GeneratorConfig generatorConfig) {
//数据库操作模板
JdbcTemplate jdbcTemplate = generatorConfig.getJdbcTemplate();
if (jdbcTemplate == null) {
//数据源
DataSource dataSource = generatorConfig.getDataSource();
if (dataSource == null)
//若数据库操作模板为空,也没有配置数据源,则抛出异常
throw new NullPointerException("数据源不能为空");
//否则以数据源创建数据库操作模板
jdbcTemplate = new JdbcTemplate(dataSource);
}
if (generatorConfig.getTransactionTemplate() == null) {
//若没有配置事务操作模板,则从配置中取事务管理器
DataSourceTransactionManager transactionManager = generatorConfig.getTransactionManager();
if (transactionManager == null) {
//若未配置事务管理器,则通过数据源新建
DataSource dataSource = jdbcTemplate.getDataSource();
if (dataSource == null)
throw new NullPointerException("数据源不能为空");
transactionManager = new DataSourceTransactionManager(dataSource);
}
//通过事务管理器创建事务操作模板
transactionTemplate = new TransactionTemplate(transactionManager);
} else {
//获取事务操作模板
transactionTemplate = generatorConfig.getTransactionTemplate();
}
this.sequencesDao = new SequencesDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.sequencesUnusedDao = new SequencesUnusedDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
this.sequencesUnlockDao = new SequencesUnlockDaoImpl(jdbcTemplate, generatorConfig.getTableConfig());
//数据
DataSource dataSource = generatorConfig.getDataSource();
if (dataSource == null)
//若数据库操作模板为空,也没有配置数据源,则抛出异常
throw new NullPointerException("数据源不能为空");
//否则以数据源创建数据库操作模板
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.sequencesDao = new SequencesDaoImpl(jdbcTemplate, generatorConfig.getTableConfig(), generatorConfig.getDbType());
this.sequencesUnusedDao = new SequencesUnusedDaoImpl(jdbcTemplate, generatorConfig.getTableConfig(), generatorConfig.getDbType());
this.sequencesUnlockDao = new SequencesUnlockDaoImpl(jdbcTemplate, generatorConfig.getTableConfig(), generatorConfig.getDbType());
this.step = generatorConfig.getStep();
this.type = generatorConfig.getType();
this.minLength = generatorConfig.getMinLength();
this.monthZeroFilling = generatorConfig.getMonthZeroFilling();
this.dayZeroFilling = generatorConfig.getDayZeroFilling();
this.dbType = generatorConfig.getDbType();
}
}

View File

@@ -1,10 +1,10 @@
package com.yanghuanglin.seq.config;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import com.yanghuanglin.seq.enums.DbType;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 生成器配置
@@ -18,21 +18,6 @@ public class GeneratorConfig {
*/
private DataSource dataSource;
/**
* 数据库操作模板
*/
private JdbcTemplate jdbcTemplate;
/**
* 事务处理模板
*/
private TransactionTemplate transactionTemplate;
/**
* 事务管理器
*/
private DataSourceTransactionManager transactionManager;
/**
* 自动创建表
*/
@@ -51,13 +36,28 @@ public class GeneratorConfig {
/**
* 默认序号类型
*/
private String type="DEFAULT";
private String type = "DEFAULT";
/**
* 月份是否补零。为false时1月显示为1为true时1月显示为01
*/
private Boolean monthZeroFilling = true;
/**
* 日期是否补零。为false时1日显示为1为true时1日显示为01
*/
private Boolean dayZeroFilling = true;
/**
* 表和字段配置
*/
private TableConfig tableConfig = new TableConfig();
/**
* 数据库类型默认情况下根据dataSource中的DatabaseProductName自动获取
*/
private DbType dbType = null;
public GeneratorConfig() {
}
@@ -73,30 +73,6 @@ public class GeneratorConfig {
this.dataSource = dataSource;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public TransactionTemplate getTransactionTemplate() {
return transactionTemplate;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
public DataSourceTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(DataSourceTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public Boolean getAutoCreate() {
return autoCreate;
}
@@ -131,6 +107,22 @@ public class GeneratorConfig {
this.step = step;
}
public Boolean getMonthZeroFilling() {
return monthZeroFilling;
}
public void setMonthZeroFilling(Boolean monthZeroFilling) {
this.monthZeroFilling = monthZeroFilling;
}
public Boolean getDayZeroFilling() {
return dayZeroFilling;
}
public void setDayZeroFilling(Boolean dayZeroFilling) {
this.dayZeroFilling = dayZeroFilling;
}
public TableConfig getTableConfig() {
return tableConfig;
}
@@ -138,4 +130,21 @@ public class GeneratorConfig {
public void setTableConfig(TableConfig tableConfig) {
this.tableConfig = tableConfig;
}
public DbType getDbType() {
if (this.dbType == null) {
try {
Connection connection = dataSource.getConnection();
String productName = connection.getMetaData().getDatabaseProductName();
this.dbType = DbType.of(productName);
} catch (SQLException e) {
throw new RuntimeException("获取数据库类型失败", e);
}
}
return dbType;
}
public void setDbType(DbType dbType) {
this.dbType = dbType;
}
}

View File

@@ -13,7 +13,7 @@ public class TableConfig {
private String table = "sequences";
/**
* 序号英文名称,和序号类型组成唯一组件
* 序号英文名称,和序号类型组成唯一主键
*/
private String keyColumn = "key";
@@ -32,6 +32,11 @@ public class TableConfig {
*/
private String createTimeColumn = "create_time";
/**
* 序号表中最后使用时间
*/
private String updateTimeColumn = "update_time";
public String getTable() {
return table;
}
@@ -71,4 +76,12 @@ public class TableConfig {
public void setCreateTimeColumn(String createTimeColumn) {
this.createTimeColumn = createTimeColumn.toLowerCase();
}
public String getUpdateTimeColumn() {
return updateTimeColumn;
}
public void setUpdateTimeColumn(String updateTimeColumn) {
this.updateTimeColumn = updateTimeColumn;
}
}

View File

@@ -22,5 +22,8 @@ public interface SequencesDao {
*/
boolean update(Sequences sequences);
/**
* 创建表
*/
void createTable();
}

View File

@@ -10,6 +10,11 @@ import java.util.List;
* @since 2022/1/28
*/
public interface SequencesUnlockDao {
/**
* 查找某个未被锁定的序号
*/
SequencesUnlock find(SequencesUnlock sequencesUnlock);
/**
* 保存使用中的序号
*/
@@ -40,5 +45,8 @@ public interface SequencesUnlockDao {
*/
boolean deleteByDate(Date begin, Date end);
/**
* 创建表
*/
void createTable();
}

View File

@@ -11,6 +11,11 @@ import java.util.List;
*/
public interface SequencesUnusedDao {
/**
* 查找某个未被使用的序号
*/
SequencesUnused find(SequencesUnused sequencesUnused);
/**
* 根据keytype查找seq最小的空闲序号
*/
@@ -36,6 +41,9 @@ public interface SequencesUnusedDao {
*/
boolean saveBatch(List<SequencesUnused> sequencesUnusedList);
/**
* 创建表
*/
void createTable();
/**

View File

@@ -0,0 +1,98 @@
package com.yanghuanglin.seq.dao.impl;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.enums.DbType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import javax.sql.DataSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
public abstract class SequencesBase {
protected DbType dbType;
protected JdbcTemplate jdbcTemplate;
protected DataSource dataSource;
protected TableConfig tableConfig;
public SequencesBase(JdbcTemplate jdbcTemplate, TableConfig tableConfig, DbType dbType) {
this.jdbcTemplate = jdbcTemplate;
this.dataSource = jdbcTemplate.getDataSource();
this.tableConfig = tableConfig;
this.dbType = dbType;
}
/**
* 执行sql文件来创建表
*
* @param fileName 文件名,在 resources/数据库类型/ 下
*/
public void createTableByFile(String fileName) {
try {
Resource resource = new ClassPathResource(dbType.getSeries() + "/" + fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append(System.lineSeparator());
}
String sql = content.toString();
switch (dbType) {
case MySQL:
sql = sql.replaceAll("`sequences(_unused|_unlock)`", String.format("%s$1", tableConfig.getTable()));
sql = sql.replaceAll("`key`", String.format("`%s`", tableConfig.getKeyColumn()));
sql = sql.replaceAll("`type`", String.format("`%s`", tableConfig.getTypeColumn()));
sql = sql.replaceAll("`seq`", String.format("`%s`", tableConfig.getSeqColumn()));
sql = sql.replaceAll("`create_time`", String.format("`%s`", tableConfig.getCreateTimeColumn()));
break;
case DM_DBMS:
case PostgreSQL:
case KingbaseES:
sql = sql.replaceAll("\"sequences(_unused|_unlock)\"", String.format("%s$1", tableConfig.getTable()));
sql = sql.replaceAll("\"key\"", String.format("\"%s\"", tableConfig.getKeyColumn()));
sql = sql.replaceAll("\"type\"", String.format("\"%s\"", tableConfig.getTypeColumn()));
sql = sql.replaceAll("\"seq\"", String.format("\"%s\"", tableConfig.getSeqColumn()));
sql = sql.replaceAll("\"create_time\"", String.format("\"%s\"", tableConfig.getCreateTimeColumn()));
break;
}
InputStream inputStream = new ByteArrayInputStream(sql.getBytes(StandardCharsets.UTF_8));
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(new InputStreamResource(inputStream));
if (Objects.equals(dbType.getSeries(), DbType.DM_DBMS.getSeries()) && fileName.endsWith("trigger.sql")) {
// 触发器文件不要通过;分隔,整个文件一起执行
databasePopulator.setSeparator(ScriptUtils.EOF_STATEMENT_SEPARATOR);
} else if (Objects.equals(dbType.getSeries(), DbType.PostgreSQL.getSeries()) && fileName.endsWith("function.sql")) {
// 函数文件不要通过;分隔,整个文件一起执行
databasePopulator.setSeparator(ScriptUtils.EOF_STATEMENT_SEPARATOR);
}
databasePopulator.execute(dataSource);
} catch (IOException e) {
System.err.println("执行SQL文件" + fileName + "失败");
}
}
/**
* 根据数据库类型简单处理sql语句
*
* @param sqlString sql语句
* @return 处理后的语句
*/
protected String dbAdapter(String sqlString) {
switch (dbType) {
case MySQL:
break;
case PostgreSQL:
case DM_DBMS:
case KingbaseES:
sqlString = sqlString.replaceAll("`(.+?)`", "\"$1\"");
break;
}
return sqlString;
}
}

View File

@@ -2,23 +2,23 @@ package com.yanghuanglin.seq.dao.impl;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesDao;
import com.yanghuanglin.seq.enums.DbType;
import com.yanghuanglin.seq.po.Sequences;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Objects;
/**
* @author yanghuanglin
* @since 2022/1/28
*/
@SuppressWarnings("SqlResolve")
public class SequencesDaoImpl implements SequencesDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
@SuppressWarnings({"SqlResolve", "SqlSourceToSinkFlow"})
public class SequencesDaoImpl extends SequencesBase implements SequencesDao {
public SequencesDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig) {
this.jdbcTemplate = jdbcTemplate;
this.tableConfig = tableConfig;
public SequencesDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig, DbType dbType) {
super(jdbcTemplate, tableConfig, dbType);
}
@Override
@@ -26,11 +26,12 @@ public class SequencesDaoImpl implements SequencesDao {
String sql = "select * from `%s` where `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn());
try {
return this.jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
return this.jdbcTemplate.queryForObject(dbAdapter(sql), (rs, rowNum) -> {
Sequences result = new Sequences();
result.setKey(rs.getString(tableConfig.getKeyColumn()));
result.setType(rs.getString(tableConfig.getTypeColumn()));
result.setSeq(rs.getLong(tableConfig.getSeqColumn()));
result.setUpdateTime(rs.getDate(tableConfig.getUpdateTimeColumn()));
return result;
}, sequences.getKey(), sequences.getType());
} catch (EmptyResultDataAccessException ignored) {
@@ -42,7 +43,7 @@ public class SequencesDaoImpl implements SequencesDao {
public boolean save(Sequences sequences) {
String sql = "insert into `%s`(`%s`,`%s`,`%s`) values(?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
int result = this.jdbcTemplate.update(sql, sequences.getKey(), sequences.getType(), sequences.getSeq());
int result = this.jdbcTemplate.update(dbAdapter(sql), sequences.getKey(), sequences.getType(), sequences.getSeq());
return result != 0;
}
@@ -50,24 +51,18 @@ public class SequencesDaoImpl implements SequencesDao {
public boolean update(Sequences sequences) {
String sql = "update `%s` set `%s`=? where `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getSeqColumn(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn());
int result = this.jdbcTemplate.update(sql, sequences.getSeq(), sequences.getKey(), sequences.getType());
int result = this.jdbcTemplate.update(dbAdapter(sql), sequences.getSeq(), sequences.getKey(), sequences.getType());
return result != 0;
}
@Override
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s` ( " +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 20 ) NOT NULL COMMENT '已使用到的序号'," +
" PRIMARY KEY ( `%s`, `%s` ) " +
" ) COMMENT '当前序号表'";
sql = String.format(sql, tableConfig.getTable(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn());
this.jdbcTemplate.execute(sql);
this.createTableByFile("create_table_sequences.sql");
if (Objects.equals(dbType.getSeries(), DbType.DM_DBMS.getSeries())) {
this.createTableByFile("create_table_sequences_trigger.sql");
} else if (Objects.equals(dbType.getSeries(), DbType.PostgreSQL.getSeries())) {
this.createTableByFile("create_table_sequences_function.sql");
this.createTableByFile("create_table_sequences_trigger.sql");
}
}
}

View File

@@ -2,7 +2,9 @@ package com.yanghuanglin.seq.dao.impl;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesUnlockDao;
import com.yanghuanglin.seq.enums.DbType;
import com.yanghuanglin.seq.po.SequencesUnlock;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
@@ -13,37 +15,57 @@ import java.util.List;
* @author yanghuanglin
* @since 2022/1/28
*/
@SuppressWarnings("SqlResolve")
public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
@SuppressWarnings({"SqlResolve", "SqlSourceToSinkFlow"})
public class SequencesUnlockDaoImpl extends SequencesBase implements SequencesUnlockDao {
public SequencesUnlockDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig) {
this.jdbcTemplate = jdbcTemplate;
this.tableConfig = tableConfig;
public SequencesUnlockDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig, DbType dbType) {
super(jdbcTemplate, tableConfig, dbType);
}
@Override
public SequencesUnlock find(SequencesUnlock sequencesUnlock) {
String sql = "select * from `%s_unlock` where `%s`=? and `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
try {
return this.jdbcTemplate.queryForObject(dbAdapter(sql), (rs, rowNum) -> {
SequencesUnlock result = new SequencesUnlock();
result.setKey(rs.getString(tableConfig.getKeyColumn()));
result.setType(rs.getString(tableConfig.getTypeColumn()));
result.setSeq(rs.getLong(tableConfig.getSeqColumn()));
result.setCreateTime(rs.getDate(tableConfig.getCreateTimeColumn()));
return result;
}, sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq());
} catch (EmptyResultDataAccessException ignored) {
return null;
}
}
@Override
public boolean save(SequencesUnlock sequencesUnlock) {
String sql = "insert into `%s_unlock`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn(), tableConfig.getCreateTimeColumn());
int result = this.jdbcTemplate.update(sql, sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq(), sequencesUnlock.getCreateTime());
int result = this.jdbcTemplate.update(dbAdapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq(), sequencesUnlock.getCreateTime());
return result != 0;
}
@Override
public boolean delete(SequencesUnlock sequencesUnlock) {
String sql = "delete from `%s_unlock` where `%s`=? and `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
int result = this.jdbcTemplate.update(sql, sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq());
return result != 0;
String sql = "delete from `%s_unlock` where `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn());
if (sequencesUnlock.getSeq() != null) {
sql += " and `%s`=?";
sql = String.format(sql, tableConfig.getSeqColumn());
return this.jdbcTemplate.update(dbAdapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq()) != 0;
} else {
return this.jdbcTemplate.update(dbAdapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType()) != 0;
}
}
@Override
public List<SequencesUnlock> listAll() {
String sql = "select * from `%s_unlock`";
sql = String.format(sql, tableConfig.getTable());
return this.jdbcTemplate.query(sql, rowMapper());
return this.jdbcTemplate.query(dbAdapter(sql), rowMapper());
}
@Override
@@ -52,15 +74,15 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
if (begin != null && end != null) {
sql = "select * from `%s_unlock` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), begin, end);
return this.jdbcTemplate.query(dbAdapter(sql), rowMapper(), begin, end);
} else if (begin != null) {
sql = "select * from `%s_unlock` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), begin);
return this.jdbcTemplate.query(dbAdapter(sql), rowMapper(), begin);
} else if (end != null) {
sql = "select * from `%s_unlock` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), end);
return this.jdbcTemplate.query(dbAdapter(sql), rowMapper(), end);
} else {
return listAll();
}
@@ -70,7 +92,7 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
public boolean deleteAll() {
String sql = "delete from `%s_unlock`";
sql = String.format(sql, tableConfig.getTable());
int result = this.jdbcTemplate.update(sql);
int result = this.jdbcTemplate.update(dbAdapter(sql));
return result != 0;
}
@@ -80,15 +102,15 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
if (begin != null && end != null) {
sql = "delete from `%s_unlock` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin, end) != 0;
return this.jdbcTemplate.update(dbAdapter(sql), begin, end) != 0;
} else if (begin != null) {
sql = "delete from `%s_unlock` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin) != 0;
return this.jdbcTemplate.update(dbAdapter(sql), begin) != 0;
} else if (end != null) {
sql = "delete from `%s_unlock` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, end) != 0;
return this.jdbcTemplate.update(dbAdapter(sql), end) != 0;
} else {
return deleteAll();
}
@@ -96,22 +118,7 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
@Override
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s_unlock` ( " +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 20 ) NOT NULL COMMENT '尚未锁定的序号'," +
" `%s` DATETIME NOT NULL COMMENT '使用时间'," +
" PRIMARY KEY ( `%s`, `%s` ,`%s` ) " +
" ) COMMENT '未锁定序号表'";
sql = String.format(sql, tableConfig.getTable(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn(),
tableConfig.getCreateTimeColumn(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn());
this.jdbcTemplate.execute(sql);
this.createTableByFile("create_table_sequences_unlock.sql");
}
private RowMapper<SequencesUnlock> rowMapper() {

View File

@@ -2,6 +2,7 @@ package com.yanghuanglin.seq.dao.impl;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesUnusedDao;
import com.yanghuanglin.seq.enums.DbType;
import com.yanghuanglin.seq.po.SequencesUnused;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
@@ -18,14 +19,29 @@ import java.util.List;
* @author yanghuanglin
* @since 2022/1/28
*/
@SuppressWarnings("SqlResolve")
public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
@SuppressWarnings({"SqlResolve", "SqlSourceToSinkFlow"})
public class SequencesUnusedDaoImpl extends SequencesBase implements SequencesUnusedDao {
public SequencesUnusedDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig) {
this.jdbcTemplate = jdbcTemplate;
this.tableConfig = tableConfig;
public SequencesUnusedDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig, DbType dbType) {
super(jdbcTemplate, tableConfig, dbType);
}
@Override
public SequencesUnused find(SequencesUnused sequencesUnused) {
String sql = "select * from `%s_unused` where `%s`=? and `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
try {
return this.jdbcTemplate.queryForObject(dbAdapter(sql), (rs, rowNum) -> {
SequencesUnused result = new SequencesUnused();
result.setKey(rs.getString(tableConfig.getKeyColumn()));
result.setType(rs.getString(tableConfig.getTypeColumn()));
result.setSeq(rs.getLong(tableConfig.getSeqColumn()));
result.setCreateTime(rs.getDate(tableConfig.getCreateTimeColumn()));
return result;
}, sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq());
} catch (EmptyResultDataAccessException ignored) {
return null;
}
}
@Override
@@ -33,7 +49,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
String sql = "select * from `%s_unused` where `%s`=? and `%s`=? order by `%s` asc limit 0,1";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
try {
return this.jdbcTemplate.queryForObject(sql, rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
return this.jdbcTemplate.queryForObject(dbAdapter(sql), rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
} catch (EmptyResultDataAccessException ignored) {
return null;
}
@@ -44,7 +60,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
try {
String sql = "select * from `%s_unused` where `%s`=? and `%s`=? order by `%s` desc limit 0,1";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
return this.jdbcTemplate.queryForObject(sql, rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
return this.jdbcTemplate.queryForObject(dbAdapter(sql), rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
} catch (EmptyResultDataAccessException ignored) {
return null;
}
@@ -54,7 +70,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
public boolean delete(SequencesUnused sequencesUnused) {
String sql = "delete from `%s_unused` where `%s`=? and `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
int result = this.jdbcTemplate.update(sql, sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq());
int result = this.jdbcTemplate.update(dbAdapter(sql), sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq());
return result != 0;
}
@@ -62,7 +78,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
public boolean save(SequencesUnused sequencesUnused) {
String sql = "insert into `%s_unused`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn(), tableConfig.getCreateTimeColumn());
int result = this.jdbcTemplate.update(sql, sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq(), sequencesUnused.getCreateTime());
int result = this.jdbcTemplate.update(dbAdapter(sql), sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq(), sequencesUnused.getCreateTime());
return result != 0;
}
@@ -70,7 +86,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
public boolean saveBatch(List<SequencesUnused> sequencesUnusedList) {
String sql = "insert into `%s_unused`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn(), tableConfig.getCreateTimeColumn());
int[] result = this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
int[] result = this.jdbcTemplate.batchUpdate(dbAdapter(sql), new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
SequencesUnused sequencesUnused = sequencesUnusedList.get(i);
@@ -90,29 +106,14 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
@Override
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s_unused` ( " +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号英文名称'," +
" `%s` VARCHAR ( 64 ) NOT NULL COMMENT '序号类型'," +
" `%s` BIGINT ( 20 ) NOT NULL COMMENT '闲置的的序号'," +
" `%s` DATETIME NOT NULL COMMENT '设为闲置序号的时间'," +
" PRIMARY KEY ( `%s`, `%s`, `%s` ) " +
" ) COMMENT '闲置序号表'";
sql = String.format(sql, tableConfig.getTable(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn(),
tableConfig.getCreateTimeColumn(),
tableConfig.getKeyColumn(),
tableConfig.getTypeColumn(),
tableConfig.getSeqColumn());
this.jdbcTemplate.execute(sql);
this.createTableByFile("create_table_sequences_unused.sql");
}
@Override
public boolean deleteAll() {
String sql = "delete from `%s_unused`";
sql = String.format(sql, tableConfig.getTable());
int result = this.jdbcTemplate.update(sql);
int result = this.jdbcTemplate.update(dbAdapter(sql));
return result != 0;
}
@@ -122,15 +123,15 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
if (begin != null && end != null) {
sql = "delete from `%s_unused` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin, end) != 0;
return this.jdbcTemplate.update(dbAdapter(sql), begin, end) != 0;
} else if (begin != null) {
sql = "delete from `%s_unused` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, begin) != 0;
return this.jdbcTemplate.update(dbAdapter(sql), begin) != 0;
} else if (end != null) {
sql = "delete from `%s_unused` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, end) != 0;
return this.jdbcTemplate.update(dbAdapter(sql), end) != 0;
} else {
return deleteAll();
}

View File

@@ -0,0 +1,37 @@
package com.yanghuanglin.seq.enums;
public enum DbType {
//MySQL数据库
MySQL("mysql"),
//达梦数据库
DM_DBMS("dm"),
//人大金仓数据库
KingbaseES("pgsql"),
//PostgreSQL数据库
PostgreSQL("pgsql");
private final String series;
DbType(String series) {
this.series = series;
}
public String getSeries() {
return series;
}
/**
* 根据数据库类型获取对应枚举
*
* @param productName 数据库类型
* @return 枚举
*/
public static DbType of(String productName) {
for (DbType value : DbType.values()) {
if (value.name().equalsIgnoreCase(productName.replace(" ", "_"))) {
return value;
}
}
throw new RuntimeException("不支持的数据库类型");
}
}

View File

@@ -22,6 +22,11 @@ public enum FormatPlaceholder {
*/
DAY("#day#"),
/**
* 序号格式字符中的固定字符串
*/
FIX("#fix#"),
/**
* 序号格式字符中的格式化后的序号
*/

View File

@@ -10,6 +10,14 @@ import com.yanghuanglin.seq.po.SequencesUnused;
import java.util.Date;
public interface Generator {
/**
* 判断格式定义中是否有序号
*
* @param pattern 格式
* @return 是否包含序号
*/
boolean containSeq(String pattern);
/**
* 根据传入的key和type生成可用的序号对象。
* <p/>
@@ -18,9 +26,15 @@ public interface Generator {
* 如果根据key和默认的{@link GeneratorConfig#getType()}在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @param key 数据字典中的编码
* @param withOutSeq 序号对象不包含序号,其值通过{@link #containSeq(String)}来判断
* @return 可用的序号对象
*/
Sequences generate(String key, Boolean withOutSeq);
/**
* 同 {@link #generate(String, Boolean)}第二个参数默认为false
*/
Sequences generate(String key);
/**
@@ -31,28 +45,40 @@ public interface Generator {
* 如果根据key和type在{@link Sequences}中找到了记录,且在{@link SequencesUnused}也找到了记录,说明该组合生成的序号有部分未使用,返回的是{@link SequencesUnused}中找到的seq最小的序号对象。同时会将{@link SequencesUnused}中找到的seq最小的记录删除然后写入到{@link SequencesUnlock}中。
* <p/>
*
* @param key 数据字典中的编码
* @param type 序号类型
* @param key 数据字典中的编码
* @param type 序号类型
* @param withOutSeq 序号对象不包含序号,其值通过{@link #containSeq(String)}来判断
* @return 可用的序号对象
*/
Sequences generate(String key, String type, Boolean withOutSeq);
/**
* 同{@link #generate(String, String, Boolean)}第三个参数默认为false
*/
Sequences generate(String key, String type);
/**
* 返回根据{@link #generate(String, String)}得到的序号对象,补零后的序号字符串
* 返回根据{@link #generate(String, String, Boolean)}得到的序号对象,补零后的序号字符串
* <p/>
* 如生成的为3而minLength为5则返回的是00003
*
* @param key 数据字典中的编码
* @param type 序号类型
* @param minLength 序号数字最小长度
* @param key 数据字典中的编码
* @param type 序号类型
* @param minLength 序号数字最小长度
* @param withOutSeq 序号对象不包含序号,其值通过{@link #containSeq(String)}来判断
* @return 补零后的字符串
*/
String generate(String key, String type, Integer minLength, Boolean withOutSeq);
/**
* 同{@link #generate(String, String, Integer, Boolean)}第四个参数默认为false
*/
String generate(String key, String type, Integer minLength);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param pattern 格式
@@ -61,9 +87,9 @@ public interface Generator {
String format(Sequences sequences, String pattern);
/**
* 将{@link #generate(String, String)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
*
* @param sequences 生成的序号对象
* @param minLength 序号数字最小长度
@@ -75,7 +101,7 @@ public interface Generator {
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR#getPlaceholder()}(当前年份)、{@link FormatPlaceholder#MONTH#getPlaceholder()}(当前月份)、{@link FormatPlaceholder#DAY#getPlaceholder()}(当前日期)、{@link FormatPlaceholder#SEQ#getPlaceholder()}(生成的字符串序号)四个变量
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下
* <p/>
@@ -90,7 +116,7 @@ public interface Generator {
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/>
@@ -106,44 +132,64 @@ public interface Generator {
/**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param fix 序号中的固定字符串
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, String pattern);
String format(Long seq, String fix, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头
* @param fix 序号中的固定字符串
* @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式
* @return 格式化后的序号字符串
*/
String format(Long seq, String start, Integer minLength, String pattern);
String format(Long seq, String fix, Integer minLength, String pattern);
/**
* 将生成的序号对象格式化为指定格式
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
*
* @param seq 需要格式化的序号
* @param fix 序号中的固定字符串
* @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式
* @param year 格式化时使用的年
* @param month 格式化时使用的月
* @param day 格式化时使用的日
* @return 格式化后的序号字符串
*/
String format(Long seq, String fix, Integer minLength, String pattern, Integer year, Integer month, Integer day);
/**
* 将已格式化的序号解析为序号对象
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}}(当前月份)、{@link FormatPlaceholder#DAY}}(当前日期)、{@link FormatPlaceholder#SEQ}}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}可能有值
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}可能有值
* <p/>
* 如果生成序号时序号的key在年、月、日上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}进行组合进而得到key
* 如果生成序号时序号的key在年、月、日、固定字符串上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}进行组合进而得到key
* <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/>
@@ -155,10 +201,38 @@ public interface Generator {
*/
Sequences parse(String formatted, String pattern);
/**
* 将已格式化的序号解析为序号对象
* <p/>
* pattern支持{@link FormatPlaceholder#YEAR}(当前年份)、{@link FormatPlaceholder#MONTH}(当前月份)、{@link FormatPlaceholder#DAY}(当前日期)、{@link FormatPlaceholder#FIX}(固定字符串)、{@link FormatPlaceholder#SEQ}(生成的字符串序号)几个枚举值通过{@link FormatPlaceholder#getPlaceholder()}得到的字符串
* <p/>
* 返回的序号对象{@link Sequences#getKey()}为null{@link Sequences#getType()}为{@link GeneratorConfig#getType()}的默认值,但是临时字段{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}可能有值
* <p/>
* 如果生成序号时序号的key在年、月、日、固定字符串上有关联如每年每月的序号要从1开始则需要自行用序号字符串与{@link Sequences#getYear()}、{@link Sequences#getMonth()}、{@link Sequences#getDay()}、{@link Sequences#getFix()}进行组合进而得到key
* <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/>
* 注意:序号格式和格式化后的字符串占位一定要匹配。如:处〔#year##month#10801第#seq#号 对应 处20220210801第10001号而不能对应 处2022021110801第10001号
*
* @param formatted 格式化后的序号字符串
* @param pattern 序号格式
* @param fixLength 序号中的固定字符串的长度
* @return 包含了序号字符串对应年如果有、月如果有、日如果有、固定字符串如果有、序号的序号对象其key需要根据情况手动设置type为{@link GeneratorConfig#getType()}的默认值
*/
Sequences parse(String formatted, String pattern, Integer fixLength);
/**
* 查询序号是否已被锁定
*
* @param sequences 需要查询的序号
* @return 锁定结果
*/
boolean locked(Sequences sequences);
/**
* 锁定指定序号,在序号生成后,调用该序号的逻辑完成后需要执行此方法
* <p/>
* 如办理案件时,先调用{@link #generate(String, String)}或者{@link #generate(String, String, Integer)}生成了序号,之后对案件进行了入库,如果入库完毕,则将该序号锁定,说明这个序号已被使用
* 如办理案件时,先调用{@link #generate(String, String, Boolean)}或者{@link #generate(String, String, Integer, Boolean)}生成了序号,之后对案件进行了入库,如果入库完毕,则将该序号锁定,说明这个序号已被使用
* <p/>
* 注意,此处的锁定非数据库中锁定,而是{@link SequencesUnused}和{@link SequencesUnlock}中均不存在key、type、seq相同的记录视为锁定。因此此处实际是把这两个表中的记录均删除了
*
@@ -167,12 +241,31 @@ public interface Generator {
*/
boolean lock(Sequences sequences);
/**
* 忽略{@link Sequences#getSeq()} ,仅通过{@link Sequences#getKey()}和{@link Sequences#getType()}来锁定序号。
* <p/>
* 如果ignoreSeq为false则等价于{@link #lock(Sequences)}
*
* @param sequences 需要锁定的序号
* @param ignoreSeq 是否忽略序号
* @return 锁定结果
*/
boolean lock(Sequences sequences, boolean ignoreSeq);
/**
* 将序号设为未使用
*
* @param sequences 需要设为未使用的序号
* @return 设置结果
*/
boolean unused(Sequences sequences);
/**
* 释放所有未使用的序号
* <p/>
* {@link SequencesUnlock}中未通过{@link #lock(Sequences)}方法锁定的序号会一直存在,调用此方法会将里面的所有序号都移动到{@link SequencesUnused}中,下次生成序号时优先从{@link SequencesUnused}获取。
*/
void release();
boolean release();
/**
* 释放指定时间段内未使用的序号
@@ -182,7 +275,7 @@ public interface Generator {
* @param begin 开始时间
* @param end 结束时间
*/
void release(Date begin, Date end);
boolean release(Date begin, Date end);
/**
* 释放从开始时间开始,到现在时间之间未使用的序号。结束时间为方法执行时的时间
@@ -203,17 +296,27 @@ public interface Generator {
*
* @param sequences 需要释放的序号。一般是一个通过{@link Sequences#setKey(String)}、{@link Sequences#setType(String)}、{@link Sequences#setSeq(Long)}三方法一起手动构建或通过{@link Sequences#Sequences(String, String, Long)}构造方法构建的实例对象
*/
void release(Sequences sequences);
boolean release(Sequences sequences);
/**
* 忽略{@link Sequences#getSeq()}来释放指定序号。一般用于业务对象删除后,对应序号需要回收使用时。
* <p/>
* 如果ignoreSeq为false则等价于{@link #release(Sequences)}
*
* @param sequences 需要释放的序号。一般是一个通过{@link Sequences#setKey(String)}、{@link Sequences#setType(String)}、{@link Sequences#setSeq(Long)}三方法一起手动构建或通过{@link Sequences#Sequences(String, String, Long)}构造方法构建的实例对象
* @param ignoreSeq 是否忽略序号
*/
boolean release(Sequences sequences, boolean ignoreSeq);
/**
* 清空所有闲置序号和未锁定序号
*/
void clear();
boolean clear();
/**
* 清空指定时间段内闲置序号和未锁定序号
*/
void clear(Date begin, Date end);
boolean clear(Date begin, Date end);
/**
* 清空从开始时间到限制时间之间闲置序号和未锁定序号,结束时间为方法执行时的时间
@@ -228,4 +331,9 @@ public interface Generator {
* @param end 结束时间
*/
void clearBefore(Date end);
/**
* 创建表
*/
void createTable();
}

View File

@@ -22,6 +22,7 @@ import java.util.regex.Pattern;
import static com.yanghuanglin.seq.enums.FormatPlaceholder.*;
@SuppressWarnings("CallToPrintStackTrace")
public class SequencesGenerator implements Generator {
private final TransactionTemplate transactionTemplate;
private final SequencesDao sequencesDao;
@@ -30,6 +31,8 @@ public class SequencesGenerator implements Generator {
private final Integer step;
private final String type;
private final Integer minLength;
private final Boolean monthZeroFilling;
private final Boolean dayZeroFilling;
public SequencesGenerator(GeneratorConfig generatorConfig) {
BaseConfig baseConfig = BaseConfig.getInstance(generatorConfig);
@@ -41,6 +44,8 @@ public class SequencesGenerator implements Generator {
this.step = baseConfig.getStep();
this.type = baseConfig.getType();
this.minLength = baseConfig.getMinLength();
this.monthZeroFilling = baseConfig.getMonthZeroFilling();
this.dayZeroFilling = baseConfig.getDayZeroFilling();
createTable(generatorConfig.getAutoCreate());
}
@@ -53,54 +58,77 @@ public class SequencesGenerator implements Generator {
private synchronized void createTable(Boolean autoCreate) {
if (!autoCreate)
return;
this.createTable();
}
@Override
public synchronized void createTable() {
this.sequencesDao.createTable();
this.sequencesUnusedDao.createTable();
this.sequencesUnlockDao.createTable();
}
@Override
public synchronized Sequences generate(String key) {
return generate(key, type);
public boolean containSeq(String pattern) {
return StringUtils.hasLength(pattern) && pattern.contains(SEQ.getPlaceholder());
}
@Override
public synchronized Sequences generate(String key, String type) {
public synchronized Sequences generate(String key, Boolean withOutSeq) {
return generate(key, type, withOutSeq);
}
@Override
public Sequences generate(String key) {
return generate(key, false);
}
@Override
public synchronized Sequences generate(String key, String type, Boolean withOutSeq) {
return transactionTemplate.execute(status -> {
try {
//根据传入的key和type新生成查询条件对象
Sequences condition = new Sequences(key, type);
//找到正在使用的最大序号
Sequences sequences = sequencesDao.find(condition);
if (sequences == null) {
//不存在说明还没生成将新生成的入库此时序号为默认的0
sequences = condition;
sequencesDao.save(sequences);
}
//根据传入的key和type查找空闲编号最小的一个
SequencesUnused conditionIdle = new SequencesUnused(condition);
SequencesUnused sequencesUnused = sequencesUnusedDao.findMinSeq(conditionIdle);
if (sequencesUnused == null) {
//空闲编号不存在,说明是未生成过,序号需要增加后直接使用,同时将新生成的写入到使用中表
sequences.increase(step);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequences);
sequencesUnlock.setCreateTime(new Date());
sequencesDao.update(sequences);
sequencesUnlockDao.save(sequencesUnlock);
if (Boolean.TRUE.equals(withOutSeq)) {
//不包含序号
condition.setWithOutSeq(true);
return condition;
} else {
//空闲编号存在,说明已经生成过,序号不需要增加,直接使用。同时将该空闲编号移动到使用中表
sequences = new Sequences(sequencesUnused);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequencesUnused);
sequencesUnlock.setCreateTime(new Date());
//不是不包含序号的序号对象(有可能格式中只配置了#year##month##day#,序号就不用自增,也不用入库,直接返回即可)
//找到正在使用的最大序号
Sequences sequences = sequencesDao.find(condition);
boolean result = true;
if (sequences == null) {
//不存在说明还没生成将新生成的入库此时序号为默认的0
sequences = condition;
result = sequencesDao.save(sequences);
}
sequencesUnlockDao.save(sequencesUnlock);
sequencesUnusedDao.delete(sequencesUnused);
//根据传入的key和type查找空闲编号最小的一个
SequencesUnused conditionIdle = new SequencesUnused(condition);
SequencesUnused sequencesUnused = sequencesUnusedDao.findMinSeq(conditionIdle);
if (sequencesUnused == null) {
//空闲编号不存在,说明是未生成过,序号需要增加后直接使用,同时将新生成的写入到使用中表
sequences.increase(step);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequences);
sequencesUnlock.setCreateTime(new Date());
result = result && sequencesDao.update(sequences) &&
sequencesUnlockDao.save(sequencesUnlock);
} else {
//空闲编号存在,说明已经生成过,序号不需要增加,直接使用。同时将该空闲编号移动到使用中表
sequences = new Sequences(sequencesUnused);
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequencesUnused);
sequencesUnlock.setCreateTime(new Date());
result = result && sequencesUnlockDao.save(sequencesUnlock) &&
sequencesUnusedDao.delete(sequencesUnused);
}
sequences.setWithOutSeq(false);
return result ? sequences : null;
}
return sequences;
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
@@ -110,13 +138,23 @@ public class SequencesGenerator implements Generator {
}
@Override
public synchronized String generate(String key, String type, Integer minLength) {
Sequences sequences = this.generate(key, type);
public Sequences generate(String key, String type) {
return generate(key, type, false);
}
@Override
public synchronized String generate(String key, String type, Integer minLength, Boolean withOutSeq) {
Sequences sequences = generate(key, type, withOutSeq);
if (sequences == null)
return null;
return sequences.format(minLength);
}
@Override
public String generate(String key, String type, Integer minLength) {
return generate(key, type, minLength, false);
}
@Override
public String format(Sequences sequences, String pattern) {
return format(sequences, minLength, pattern);
@@ -138,27 +176,48 @@ public class SequencesGenerator implements Generator {
}
@Override
public String format(Long seq, String start, String pattern) {
return format(seq, start, minLength, pattern);
public String format(Long seq, String fix, String pattern) {
return format(seq, fix, minLength, pattern);
}
@Override
public String format(Long seq, String start, Integer minLength, String pattern) {
if (start == null)
start = "";
String seqString = start + new Sequences(seq).format(minLength);
public String format(Long seq, String fix, Integer minLength, String pattern) {
return format(seq, fix, minLength, pattern, null, null, null);
}
@Override
public String format(Long seq, String fix, Integer minLength, String pattern, Integer year, Integer month, Integer day) {
if (fix == null)
fix = "";
String seqString = new Sequences(seq).format(minLength);
Calendar calendar = Calendar.getInstance();
pattern = pattern.replaceAll(YEAR.getPlaceholder(), String.valueOf(calendar.get(Calendar.YEAR)));
pattern = pattern.replaceAll(MONTH.getPlaceholder(), String.format("%02d", calendar.get(Calendar.MONTH) + 1));
pattern = pattern.replaceAll(DAY.getPlaceholder(), String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
if (year == null)
year = calendar.get(Calendar.YEAR);
if (month == null)
month = calendar.get(Calendar.MONTH) + 1;
if (day == null)
day = calendar.get(Calendar.DAY_OF_MONTH);
pattern = pattern.replaceAll(YEAR.getPlaceholder(), String.valueOf(year));
pattern = pattern.replaceAll(MONTH.getPlaceholder(), monthZeroFilling ? String.format("%02d", month) : String.valueOf(month));
pattern = pattern.replaceAll(DAY.getPlaceholder(), dayZeroFilling ? String.format("%02d", day) : String.valueOf(day));
pattern = pattern.replaceAll(FIX.getPlaceholder(), fix);
pattern = pattern.replaceAll(SEQ.getPlaceholder(), seqString);
return pattern;
}
@Override
public Sequences parse(String formatted, String pattern) {
return parse(formatted, pattern, null);
}
@Override
public Sequences parse(String formatted, String pattern, Integer fixLength) {
//如果解析时的格式中包含了固定字符串的占位符则其固定字符串占位符的长度必须大于0否则抛出异常。
//如果不设置固定字符串的长度,就无法将固定字符串和序号分隔开
if (pattern.contains(FIX.getPlaceholder()) && (fixLength == null || fixLength == 0))
throw new NullPointerException("请设置固定字符串的长度该长度需要大于0否则无法区分固定字符串和序号。");
//年、月、日、序号分隔特殊符号正则规则
String splitRegString = "(" + YEAR.getPlaceholder() + "|" + MONTH.getPlaceholder() + "|" + DAY.getPlaceholder() + "|" + SEQ.getPlaceholder() + ")";
String splitRegString = "(" + YEAR.getPlaceholder() + "|" + MONTH.getPlaceholder() + "|" + DAY.getPlaceholder() + "|" + FIX.getPlaceholder() + "|" + SEQ.getPlaceholder() + ")";
//根据年、月、日、序号的特殊符号,对格式进行分隔,得到排除特殊符号后的字符串数组
String[] split = pattern.split(splitRegString);
@@ -168,23 +227,25 @@ public class SequencesGenerator implements Generator {
formatted = formatted.replace(splitString, "");
}
//年、月、日的数字匹配正则规则
//年、月、日、固定字符串 匹配正则规则
String yearRegStr = "\\d{4}";
String monthRegStr = "\\d{2}";
String dayRegStr = "\\d{2}";
String fixRegStr = (fixLength == null || fixLength == 0) ? null : ".{" + fixLength + "}";
//将序号格式分隔特殊符号字符串转为正则匹配规则
Pattern seqPattern = Pattern.compile(splitRegString);
//对序号格式进行匹配
Matcher matcher = seqPattern.matcher(pattern);
//将年、月、日匹配规则字符串转为正则匹配规则
//将年、月、日、固定字符串 匹配规则字符串转为正则匹配规则
Pattern yearPattern = Pattern.compile(yearRegStr);
Pattern monthPattern = Pattern.compile(monthRegStr);
Pattern dayPattern = Pattern.compile(dayRegStr);
Pattern fixPattern = StringUtils.hasLength(fixRegStr) ? Pattern.compile(fixRegStr) : null;
//默认的年、月、日均为空字符串
String year = "", month = "", day = "", seq = "";
//默认的年、月、日、固定字符串、序号均为空字符串
String year = "", month = "", day = "", fix = "", seq = "";
//根据序号匹配规则字符串查找字符串分组
while (matcher.find()) {
String group = matcher.group();
@@ -198,7 +259,7 @@ public class SequencesGenerator implements Generator {
if (yearMatcher.find()) {
year = yearMatcher.group();
}
formatted = formatted.replaceFirst(yearRegStr, "");
formatted = formatted.replaceFirst(yearPattern.pattern(), "");
break;
case MONTH:
//若分组为月份分组则将月份正则匹配到的字符串赋值给month同时把格式化后的序号字符串中对应月的字符串替换为空字符串
@@ -206,7 +267,7 @@ public class SequencesGenerator implements Generator {
if (monthMatcher.find()) {
month = monthMatcher.group();
}
formatted = formatted.replaceFirst(monthRegStr, "");
formatted = formatted.replaceFirst(monthPattern.pattern(), "");
break;
case DAY:
//若分组为日期分组则将日期正则匹配到的字符串赋值给day同时把格式化后的序号字符串中对应日期的字符串替换为空字符串
@@ -214,7 +275,17 @@ public class SequencesGenerator implements Generator {
if (dayMatcher.find()) {
day = dayMatcher.group();
}
formatted = formatted.replaceFirst(dayRegStr, "");
formatted = formatted.replaceFirst(dayPattern.pattern(), "");
break;
case FIX:
if (fixPattern == null)
break;
//若分组为固定字符串分组则将固定字符串正则匹配到的字符串赋值给fix同时把格式化后的序号字符串中对应固定字符串的字符串替换为空字符串
Matcher fixMatcher = fixPattern.matcher(formatted);
if (fixMatcher.find()) {
fix = fixMatcher.group();
}
formatted = formatted.replaceFirst(fixPattern.pattern(), "");
break;
}
}
@@ -227,23 +298,91 @@ public class SequencesGenerator implements Generator {
sequences.setYear(StringUtils.hasLength(year) ? Integer.valueOf(year) : null);
sequences.setMonth(StringUtils.hasLength(month) ? Integer.valueOf(month) : null);
sequences.setDay(StringUtils.hasLength(day) ? Integer.valueOf(day) : null);
sequences.setFix(StringUtils.hasLength(fix) ? fix : null);
sequences.setSeq(StringUtils.hasLength(seq) ? Long.parseLong(seq) : 0L);
sequences.setWithOutSeq(!StringUtils.hasLength(seq));
sequences.setType(type);
return sequences;
}
@Override
public synchronized boolean lock(Sequences sequences) {
if (sequences == null)
public boolean locked(Sequences sequences) {
if (sequences == null || Boolean.TRUE.equals(sequences.getWithOutSeq()))
return true;
SequencesUnlock condition = new SequencesUnlock(sequences);
//将使用中表的对应数据删除,空闲表中数据在生成时会删除,因此这里不需要处理该表
return sequencesUnlockDao.delete(condition);
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
SequencesUnlock sequencesUnlock = sequencesUnlockDao.find(condition);
return sequencesUnlock == null;
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized void release() {
public synchronized boolean lock(Sequences sequences) {
if (sequences == null || Boolean.TRUE.equals(sequences.getWithOutSeq()))
return true;
SequencesUnlock condition = new SequencesUnlock(sequences);
//将使用中表的对应数据删除,空闲表中数据在生成时会删除,因此这里不需要处理该表
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
return sequencesUnlockDao.delete(condition);
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized boolean lock(Sequences sequences, boolean ignoreSeq) {
if (!ignoreSeq)
return lock(sequences);
if (sequences == null || Boolean.TRUE.equals(sequences.getWithOutSeq()))
return true;
SequencesUnlock condition = new SequencesUnlock(sequences);
condition.setSeq(null);
//将使用中表的对应数据删除,空闲表中数据在生成时会删除,因此这里不需要处理该表
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
return sequencesUnlockDao.delete(condition);
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public boolean unused(Sequences sequences) {
if (sequences == null)
return true;
SequencesUnused condition = new SequencesUnused(sequences);
condition.setCreateTime(new Date());
//在未使用中表增加需要设为未使用的序号
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
return sequencesUnusedDao.save(condition);
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized boolean release() {
//列出所有使用中表存在的序号
List<SequencesUnlock> sequencesUnlockList = sequencesUnlockDao.listAll();
@@ -253,13 +392,23 @@ public class SequencesGenerator implements Generator {
}
//将使用中表的序号放到空闲表中
sequencesUnusedDao.saveBatch(sequencesUnusedList);
//删除所有使用中表的数据
sequencesUnlockDao.deleteAll();
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
//将使用中表的序号放到空闲表中
//删除所有使用中表的数据
return sequencesUnusedDao.saveBatch(sequencesUnusedList) &&
sequencesUnlockDao.deleteAll();
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized void release(Date begin, Date end) {
public synchronized boolean release(Date begin, Date end) {
//列出指定时间段内使用中表存在的序号
List<SequencesUnlock> sequencesUnlockList = sequencesUnlockDao.listByDate(begin, end);
@@ -269,9 +418,19 @@ public class SequencesGenerator implements Generator {
}
//将指定时间段内使用中表的序号放到空闲表中
sequencesUnusedDao.saveBatch(sequencesUnusedList);
//删除指定时间段内使用中表的数据
sequencesUnlockDao.deleteByDate(begin, end);
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
//将指定时间段内使用中表的序号放到空闲表中
//删除指定时间段内使用中表的数据
return sequencesUnusedDao.saveBatch(sequencesUnusedList) &&
sequencesUnlockDao.deleteByDate(begin, end);
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
@@ -285,23 +444,68 @@ public class SequencesGenerator implements Generator {
}
@Override
public synchronized void release(Sequences sequences) {
public synchronized boolean release(Sequences sequences) {
if (sequences == null)
return;
sequencesUnlockDao.delete(new SequencesUnlock(sequences));
sequencesUnusedDao.save(new SequencesUnused(sequences, new Date()));
return true;
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
return sequencesUnlockDao.delete(new SequencesUnlock(sequences))
&& sequencesUnusedDao.save(new SequencesUnused(sequences, new Date()));
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized void clear() {
sequencesUnlockDao.deleteAll();
sequencesUnusedDao.deleteAll();
public synchronized boolean release(Sequences sequences, boolean ignoreSeq) {
if (!ignoreSeq) {
return release(sequences);
}
if (sequences == null)
return true;
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
SequencesUnlock sequencesUnlock = new SequencesUnlock(sequences);
sequencesUnlock.setSeq(null);
//由于忽略了序号因此不需要将未使用序号放到SequencesUnused里面
return sequencesUnlockDao.delete(sequencesUnlock);
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized void clear(Date begin, Date end) {
sequencesUnlockDao.deleteByDate(begin, end);
sequencesUnusedDao.deleteByDate(begin, end);
public synchronized boolean clear() {
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
return sequencesUnlockDao.deleteAll() &&
sequencesUnusedDao.deleteAll();
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override
public synchronized boolean clear(Date begin, Date end) {
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try {
return sequencesUnlockDao.deleteByDate(begin, end) &&
sequencesUnusedDao.deleteByDate(begin, end);
} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
return false;
}
}));
}
@Override

View File

@@ -2,6 +2,8 @@ package com.yanghuanglin.seq.po;
import com.yanghuanglin.seq.config.BaseConfig;
import java.util.Date;
/**
* 当前序号
*
@@ -24,6 +26,11 @@ public class Sequences {
*/
protected Long seq = 0L;
/**
* 最后使用时间
*/
private Date updateTime;
/**
* 临时字段序号对应的年份如2022年如果能获取到的话
* 该字段仅用于解析序号字符串时解析出对应年份用于合成key序号对应的key为SNT+年份,返回的为其年份)
@@ -42,6 +49,17 @@ public class Sequences {
*/
private transient Integer day;
/**
* 临时字段序号对应的固定字符串A1
* 该字段仅用于解析序号字符串时解析出对应固定字符用于合成key序号对应的key为SNT+年份+月份+日期+固定字符串,返回的为其固定字符串)
*/
private transient String fix;
/**
* 临时字段,表示序号对象不包含序号
*/
private transient Boolean withOutSeq;
public Sequences() {
}
@@ -90,6 +108,14 @@ public class Sequences {
this.seq = seq;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getYear() {
return year;
}
@@ -114,6 +140,22 @@ public class Sequences {
this.day = day;
}
public String getFix() {
return fix;
}
public void setFix(String fix) {
this.fix = fix;
}
public Boolean getWithOutSeq() {
return withOutSeq;
}
public void setWithOutSeq(Boolean withOutSeq) {
this.withOutSeq = withOutSeq;
}
/**
* 将序号增加指定步长
*
@@ -153,9 +195,12 @@ public class Sequences {
"key='" + key + '\'' +
", type='" + type + '\'' +
", seq=" + seq +
", updateTime=" + updateTime +
", year=" + year +
", month=" + month +
", day=" + day +
", fix='" + fix + '\'' +
", withOutSeq=" + withOutSeq +
'}';
}
}

View File

@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS "sequences"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" BIGINT NOT NULL,
"update_time" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ("key", "type")
);
COMMENT ON TABLE "sequences" IS '当前序号表';
COMMENT ON COLUMN "sequences"."key" IS '序号英文名称';
COMMENT ON COLUMN "sequences"."type" IS '序号类型';
COMMENT ON COLUMN "sequences"."seq" IS '已使用到的序号';
COMMENT ON COLUMN "sequences"."update_time" IS '最后使用时间';

View File

@@ -0,0 +1,8 @@
CREATE OR REPLACE TRIGGER "SEQUENCES_UPDATE_TIME"
BEFORE UPDATE
ON "sequences"
referencing OLD ROW AS "OLD" NEW ROW AS "NEW"
FOR EACH ROW
BEGIN
:NEW."UPDATE_TIME" := CURRENT_TIMESTAMP;
END;

View File

@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS "sequences_unlock"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" BIGINT NOT NULL,
"create_time" TIMESTAMP NOT NULL,
PRIMARY KEY ("key", "type", "seq")
);
COMMENT ON TABLE "sequences_unlock" IS '未锁定序号表';
COMMENT ON COLUMN "sequences_unlock"."key" IS '序号英文名称';
COMMENT ON COLUMN "sequences_unlock"."type" IS '序号类型';
COMMENT ON COLUMN "sequences_unlock"."seq" IS '尚未锁定的序号';
COMMENT ON COLUMN "sequences_unlock"."create_time" IS '使用时间';

View File

@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS "sequences_unused"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" BIGINT NOT NULL,
"create_time" TIMESTAMP NOT NULL,
PRIMARY KEY ("key", "type", "seq")
);
COMMENT ON TABLE "sequences_unused" IS '闲置序号表';
COMMENT ON COLUMN "sequences_unused"."key" IS '序号英文名称';
COMMENT ON COLUMN "sequences_unused"."type" IS '序号类型';
COMMENT ON COLUMN "sequences_unused"."seq" IS '闲置的的序号';
COMMENT ON COLUMN "sequences_unused"."create_time" IS '设为闲置序号的时间';

View File

@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `sequences`
(
`key` VARCHAR(64) NOT NULL COMMENT '序号英文名称',
`type` VARCHAR(64) NOT NULL COMMENT '序号类型',
`seq` BIGINT(20) NOT NULL COMMENT '已使用到的序号',
`update_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后使用时间',
PRIMARY KEY (`key`, `type`)
) COMMENT '当前序号表';

View File

@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `sequences_unlock`
(
`key` VARCHAR(64) NOT NULL COMMENT '序号英文名称',
`type` VARCHAR(64) NOT NULL COMMENT '序号类型',
`seq` BIGINT(20) NOT NULL COMMENT '尚未锁定的序号',
`create_time` DATETIME NOT NULL COMMENT '使用时间',
PRIMARY KEY (`key`, `type`, `seq`)
) COMMENT '未锁定序号表';

View File

@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `sequences_unused`
(
`key` VARCHAR(64) NOT NULL COMMENT '序号英文名称',
`type` VARCHAR(64) NOT NULL COMMENT '序号类型',
`seq` BIGINT(20) NOT NULL COMMENT '闲置的的序号',
`create_time` DATETIME NOT NULL COMMENT '设为闲置序号的时间',
PRIMARY KEY (`key`, `type`, `seq`)
) COMMENT '闲置序号表';

View File

@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS "sequences"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" INT8 NOT NULL,
"update_time" TIMESTAMP,
PRIMARY KEY ("key", "type")
);
COMMENT ON TABLE "sequences" IS '当前序号表';
COMMENT ON COLUMN "sequences"."key" IS '序号英文名称';
COMMENT ON COLUMN "sequences"."type" IS '序号类型';
COMMENT ON COLUMN "sequences"."seq" IS '已使用到的序号';
COMMENT ON COLUMN "sequences"."update_time" IS '最后使用时间';

View File

@@ -0,0 +1,6 @@
CREATE OR REPLACE FUNCTION SEQUENCES_UPDATE_TIME() RETURNS TRIGGER AS $$
BEGIN
NEW."update_time" := current_timestamp;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View File

@@ -0,0 +1,2 @@
DROP TRIGGER IF EXISTS SEQUENCES_UPDATE_TIME ON "sequences" CASCADE;
CREATE TRIGGER SEQUENCES_UPDATE_TIME BEFORE INSERT OR UPDATE ON "sequences" FOR EACH ROW EXECUTE PROCEDURE SEQUENCES_UPDATE_TIME();

View File

@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS "sequences_unlock"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" INT8 NOT NULL,
"create_time" TIMESTAMP NOT NULL,
PRIMARY KEY ("key", "type", "seq")
);
COMMENT ON TABLE "sequences_unlock" IS '未锁定序号表';
COMMENT ON COLUMN "sequences_unlock"."key" IS '序号英文名称';
COMMENT ON COLUMN "sequences_unlock"."type" IS '序号类型';
COMMENT ON COLUMN "sequences_unlock"."seq" IS '尚未锁定的序号';
COMMENT ON COLUMN "sequences_unlock"."create_time" IS '使用时间';

View File

@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS "sequences_unused"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" INT8 NOT NULL,
"create_time" TIMESTAMP NOT NULL,
PRIMARY KEY ("key", "type", "seq")
);
COMMENT ON TABLE "sequences_unused" IS '闲置序号表';
COMMENT ON COLUMN "sequences_unused"."key" IS '序号英文名称';
COMMENT ON COLUMN "sequences_unused"."type" IS '序号类型';
COMMENT ON COLUMN "sequences_unused"."seq" IS '闲置的的序号';
COMMENT ON COLUMN "sequences_unused"."create_time" IS '设为闲置序号的时间';

View File

@@ -1,11 +1,16 @@
import com.kingbase8.ds.KBSimpleDataSource;
import com.mysql.cj.jdbc.MysqlDataSource;
import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.generator.impl.SequencesGenerator;
import com.yanghuanglin.seq.po.Sequences;
import dm.jdbc.driver.DmdbDataSource;
import org.junit.Test;
import org.postgresql.ds.PGSimpleDataSource;
import javax.sql.DataSource;
import java.sql.DatabaseMetaData;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
@@ -17,25 +22,64 @@ import java.util.concurrent.TimeUnit;
* @since 2022/1/28
*/
public class SeqTest {
private static final MysqlDataSource dataSource = new MysqlDataSource();
private static final DataSource dataSource;
private static final Generator generator;
static {
dataSource.setURL("jdbc:mysql://127.0.0.1:3306/sequence");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource = dm();
GeneratorConfig generatorConfig = new GeneratorConfig(dataSource);
System.out.println("DbType: " + generatorConfig.getDbType());
TableConfig tableConfig = new TableConfig();
tableConfig.setTable("sequences");
tableConfig.setKeyColumn("SEQUENCE_KEY");
tableConfig.setTypeColumn("SEQUENCE_TYPE");
tableConfig.setSeqColumn("CURRENT");
generatorConfig.setTableConfig(tableConfig);
generatorConfig.setDayZeroFilling(false);
generatorConfig.setMonthZeroFilling(false);
generator = new SequencesGenerator(generatorConfig);
}
private static DataSource mysql() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/sequence");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("root");
return mysqlDataSource;
}
private static DataSource kingbase8() {
KBSimpleDataSource kbDataSource = new KBSimpleDataSource();
kbDataSource.setURL("jdbc:kingbase8://127.0.0.1:54321/cemis?currentSchema=sequence");
kbDataSource.setUser("kingbase");
kbDataSource.setPassword("kingbase");
return kbDataSource;
}
private static DataSource pgsql() {
PGSimpleDataSource pgDataSource = new PGSimpleDataSource();
pgDataSource.setURL("jdbc:postgresql://127.0.0.1:54321/cemis?currentSchema=sequence");
pgDataSource.setUser("kingbase");
pgDataSource.setPassword("kingbase");
return pgDataSource;
}
private static DataSource dm() {
DmdbDataSource dmdbDataSource = new DmdbDataSource();
dmdbDataSource.setURL("jdbc:dm://127.0.0.1:5236?schema=sequence");
dmdbDataSource.setUser("SYSDBA");
dmdbDataSource.setPassword("SYSDBA");
return dmdbDataSource;
}
@Test
public void createTable() {
generator.createTable();
}
@Test
public void generateTest() {
//释放未锁定序列号
@@ -44,15 +88,17 @@ public class SeqTest {
Set<String> set = new HashSet<>();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100));
for (int i = 0; i < 5; i++) {
int finalI = i;
final int finalI = i;
threadPoolExecutor.execute(() -> {
Sequences sequences = generator.generate("SNT", "MISSION");
String formattedSeq = generator.format(sequences.getSeq(), "处〔#year#10801#seq#");
// if (finalI % 2 == 0)
// System.out.println(3 / 0);
String pattern = "处〔#year##fix##seq#";
String fix = "10801" + finalI;
String formattedSeq = generator.format(sequences.getSeq(), fix, pattern);
generator.lock(sequences);
set.add(formattedSeq);
System.out.println(formattedSeq);
Sequences parse = generator.parse(formattedSeq, pattern, fix.length());
System.out.println(parse);
});
}
threadPoolExecutor.shutdown();
@@ -76,10 +122,11 @@ public class SeqTest {
@Test
public void parseTest() {
String seqPattern = "ZZF#year##month##seq#";
String formatted = "ZZF20220200008";
String seqPattern = "ZZF#year##month##fix##seq#";
String formatted = "ZZF202202A18";
Sequences sequences = generator.parse(formatted, seqPattern);
//A1视为固定字符串其长度为2
Sequences sequences = generator.parse(formatted, seqPattern, 2);
String key = "zzfCode" + sequences.getYear();
@@ -87,4 +134,35 @@ public class SeqTest {
sequences.setType("MISSION");
System.out.println(sequences);
}
@Test
public void unusedTest() {
Sequences sequences = new Sequences();
sequences.setKey("0010001$distrainCode2024");
sequences.setType("MISSION");
sequences.setSeq(1L);
boolean result = generator.unused(sequences);
assert result;
}
@Test
public void lockTest() {
generator.generate("0010001$distrainCode2024","MISSION");
Sequences sequences = new Sequences();
sequences.setKey("0010001$distrainCode2024");
sequences.setType("MISSION");
sequences.setSeq(1L);
boolean result = generator.lock(sequences);
assert result;
}
@Test
public void lockedTest() {
Sequences sequences = new Sequences();
sequences.setKey("0010001$distrainCode2024");
sequences.setType("MISSION");
sequences.setSeq(1L);
boolean result = generator.locked(sequences);
System.out.println("locked: " + result);
}
}