16 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
30 changed files with 810 additions and 179 deletions

View File

@@ -4,11 +4,15 @@
用于生成全局自增序号,跳过的序号可以回收使用。 用于生成全局自增序号,跳过的序号可以回收使用。
***本生成器内部使用transactionTemplate进行事务管理如果你项目中给使用此生成器的方法或类加了`@Transactional`
注解则需将新建一个Service来专门负责调用此生成器的方法同时要给新建的类增加`@Transactional`
注解,并设置`propagation = Propagation.NOT_SUPPORTED`***
--- ---
使用方法: 使用方法:
+ 在项目中放置jar包的地方把seq-1.8.2.jar、seq-1.8.2-sources.jar、seq-1.8.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 + 在pom.xml中增加以下内容然后执行maven命令mvn clean
```xml ```xml
@@ -18,7 +22,7 @@
<dependency> <dependency>
<groupId>com.yanghuanglin</groupId> <groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId> <artifactId>seq</artifactId>
<version>1.8.2</version> <version>1.9.2</version>
<exclusions> <exclusions>
<!-- 如若你项目中有引用spring-jdbc则需要排除seq的jdbc依赖 --> <!-- 如若你项目中有引用spring-jdbc则需要排除seq的jdbc依赖 -->
<exclusion> <exclusion>
@@ -50,13 +54,13 @@
</goals> </goals>
<configuration> <configuration>
<!-- ${project.basedir}表示当前项目的根目录 --> <!-- ${project.basedir}表示当前项目的根目录 -->
<file>${project.basedir}/lib/seq-1.8.2.jar</file> <file>${project.basedir}/lib/seq-1.9.2.jar</file>
<pomFile>${project.basedir}/lib/seq-1.8.2-pom.xml</pomFile> <pomFile>${project.basedir}/lib/seq-1.9.2-pom.xml</pomFile>
<sources>${project.basedir}/lib/seq-1.8.2-sources.jar</sources> <sources>${project.basedir}/lib/seq-1.9.2-sources.jar</sources>
<repositoryLayout>default</repositoryLayout> <repositoryLayout>default</repositoryLayout>
<groupId>com.yanghuanglin</groupId> <groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId> <artifactId>seq</artifactId>
<version>1.8.2</version> <version>1.9.2</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<generatePom>true</generatePom> <generatePom>true</generatePom>
</configuration> </configuration>
@@ -203,7 +207,7 @@ TableConfig配置项通过set方法设置一般不用改如果已有相
GeneratorConfig配置项通过set方法设置 GeneratorConfig配置项通过set方法设置
| 配置项 | 类型 | 默认值 | 说明 | | 配置项 | 类型 | 默认值 | 说明 |
|---------------------|------------------------------------------------------------------|------------------|------------------| |------------------|---------------------------------------------|------------------|------------------|
| dataSource | javax.sql.DataSource | null | 数据源 | | dataSource | javax.sql.DataSource | null | 数据源 |
| monthZeroFilling | Boolean | true | 月份不足2位时自动补零 | | monthZeroFilling | Boolean | true | 月份不足2位时自动补零 |
| dayZeroFilling | Boolean | true | 当前日期不足2位时自动补零 | | dayZeroFilling | Boolean | true | 当前日期不足2位时自动补零 |
@@ -297,7 +301,7 @@ public interface Generator {
/** /**
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性 * 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* <p/> * <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 sequences 生成的序号对象
* @param pattern 格式 * @param pattern 格式
@@ -308,7 +312,7 @@ public interface Generator {
/** /**
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性 * 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* <p/> * <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 sequences 生成的序号对象
* @param minLength 序号数字最小长度 * @param minLength 序号数字最小长度
@@ -320,7 +324,7 @@ public interface Generator {
/** /**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零 * 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/> * <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/> * <p/>
* seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下 * seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下
* <p/> * <p/>
@@ -335,7 +339,7 @@ public interface Generator {
/** /**
* 将生成的序号对象格式化为指定格式 * 将生成的序号对象格式化为指定格式
* <p/> * <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/> * <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下 * seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/> * <p/>
@@ -351,44 +355,64 @@ public interface Generator {
/** /**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零 * 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/> * <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/> * <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下 * seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* <p/> * <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零] * 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
* *
* @param seq 需要格式化的序号 * @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头 * @param fix 序号中的固定字符串
* @param pattern 序号格式 * @param pattern 序号格式
* @return 格式化后的序号字符串 * @return 格式化后的序号字符串
*/ */
String format(Long seq, String start, String pattern); String format(Long seq, String fix, String pattern);
/** /**
* 将生成的序号对象格式化为指定格式 * 将生成的序号对象格式化为指定格式
* <p/> * <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/> * <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下 * seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/> * <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零] * 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
* *
* @param seq 需要格式化的序号 * @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头 * @param fix 序号中的固定字符串
* @param minLength 序号最小长度,不足的会补零 * @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式 * @param pattern 序号格式
* @return 格式化后的序号字符串 * @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/> * <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/> * <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/> * <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/> * <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()} * 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/> * <p/>
@@ -400,6 +424,26 @@ public interface Generator {
*/ */
Sequences parse(String formatted, String pattern); 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/> * <p/>
@@ -495,5 +539,4 @@ public interface Generator {
*/ */
void clearBefore(Date end); void clearBefore(Date end);
} }
``` ```

36
pom.xml
View File

@@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.yanghuanglin</groupId> <groupId>com.yanghuanglin</groupId>
<artifactId>seq</artifactId> <artifactId>seq</artifactId>
<version>1.8.2</version> <version>1.13.1</version>
<name>seq</name> <name>seq</name>
<description>seq</description> <description>seq</description>
<properties> <properties>
@@ -14,12 +14,31 @@
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId> <artifactId>spring-jdbc</artifactId>
<version>5.3.15</version> <version>5.3.36</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <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>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@@ -30,6 +49,16 @@
</dependencies> </dependencies>
<build> <build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>rebel.xml</exclude>
<exclude>rebel-remote.xml</exclude>
</excludes>
</resource>
</resources>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
@@ -40,6 +69,7 @@
<target>8</target> <target>8</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <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.SequencesDaoImpl;
import com.yanghuanglin.seq.dao.impl.SequencesUnlockDaoImpl; import com.yanghuanglin.seq.dao.impl.SequencesUnlockDaoImpl;
import com.yanghuanglin.seq.dao.impl.SequencesUnusedDaoImpl; import com.yanghuanglin.seq.dao.impl.SequencesUnusedDaoImpl;
import com.yanghuanglin.seq.enums.DbType;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
@@ -30,6 +31,7 @@ public class BaseConfig {
private Integer minLength; private Integer minLength;
private Boolean monthZeroFilling; private Boolean monthZeroFilling;
private Boolean dayZeroFilling; private Boolean dayZeroFilling;
private DbType dbType;
private BaseConfig() { private BaseConfig() {
} }
@@ -161,13 +163,14 @@ public class BaseConfig {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
this.transactionTemplate = new TransactionTemplate(transactionManager); this.transactionTemplate = new TransactionTemplate(transactionManager);
this.sequencesDao = new SequencesDaoImpl(jdbcTemplate, generatorConfig.getTableConfig()); this.sequencesDao = new SequencesDaoImpl(jdbcTemplate, generatorConfig.getTableConfig(), generatorConfig.getDbType());
this.sequencesUnusedDao = new SequencesUnusedDaoImpl(jdbcTemplate, generatorConfig.getTableConfig()); this.sequencesUnusedDao = new SequencesUnusedDaoImpl(jdbcTemplate, generatorConfig.getTableConfig(), generatorConfig.getDbType());
this.sequencesUnlockDao = new SequencesUnlockDaoImpl(jdbcTemplate, generatorConfig.getTableConfig()); this.sequencesUnlockDao = new SequencesUnlockDaoImpl(jdbcTemplate, generatorConfig.getTableConfig(), generatorConfig.getDbType());
this.step = generatorConfig.getStep(); this.step = generatorConfig.getStep();
this.type = generatorConfig.getType(); this.type = generatorConfig.getType();
this.minLength = generatorConfig.getMinLength(); this.minLength = generatorConfig.getMinLength();
this.monthZeroFilling = generatorConfig.getMonthZeroFilling(); this.monthZeroFilling = generatorConfig.getMonthZeroFilling();
this.dayZeroFilling = generatorConfig.getDayZeroFilling(); this.dayZeroFilling = generatorConfig.getDayZeroFilling();
this.dbType = generatorConfig.getDbType();
} }
} }

View File

@@ -1,6 +1,10 @@
package com.yanghuanglin.seq.config; package com.yanghuanglin.seq.config;
import com.yanghuanglin.seq.enums.DbType;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/** /**
* 生成器配置 * 生成器配置
@@ -49,6 +53,11 @@ public class GeneratorConfig {
*/ */
private TableConfig tableConfig = new TableConfig(); private TableConfig tableConfig = new TableConfig();
/**
* 数据库类型默认情况下根据dataSource中的DatabaseProductName自动获取
*/
private DbType dbType = null;
public GeneratorConfig() { public GeneratorConfig() {
} }
@@ -121,4 +130,21 @@ public class GeneratorConfig {
public void setTableConfig(TableConfig tableConfig) { public void setTableConfig(TableConfig tableConfig) {
this.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

@@ -32,6 +32,11 @@ public class TableConfig {
*/ */
private String createTimeColumn = "create_time"; private String createTimeColumn = "create_time";
/**
* 序号表中最后使用时间
*/
private String updateTimeColumn = "update_time";
public String getTable() { public String getTable() {
return table; return table;
} }
@@ -71,4 +76,12 @@ public class TableConfig {
public void setCreateTimeColumn(String createTimeColumn) { public void setCreateTimeColumn(String createTimeColumn) {
this.createTimeColumn = createTimeColumn.toLowerCase(); 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); boolean update(Sequences sequences);
/**
* 创建表
*/
void createTable(); void createTable();
} }

View File

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

View File

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

View File

@@ -2,7 +2,9 @@ package com.yanghuanglin.seq.dao.impl;
import com.yanghuanglin.seq.config.TableConfig; import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesUnlockDao; import com.yanghuanglin.seq.dao.SequencesUnlockDao;
import com.yanghuanglin.seq.enums.DbType;
import com.yanghuanglin.seq.po.SequencesUnlock; import com.yanghuanglin.seq.po.SequencesUnlock;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
@@ -13,21 +15,36 @@ import java.util.List;
* @author yanghuanglin * @author yanghuanglin
* @since 2022/1/28 * @since 2022/1/28
*/ */
@SuppressWarnings("SqlResolve") @SuppressWarnings({"SqlResolve", "SqlSourceToSinkFlow"})
public class SequencesUnlockDaoImpl implements SequencesUnlockDao { public class SequencesUnlockDaoImpl extends SequencesBase implements SequencesUnlockDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
public SequencesUnlockDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig) { public SequencesUnlockDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig, DbType dbType) {
this.jdbcTemplate = jdbcTemplate; super(jdbcTemplate, tableConfig, dbType);
this.tableConfig = tableConfig; }
@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 @Override
public boolean save(SequencesUnlock sequencesUnlock) { public boolean save(SequencesUnlock sequencesUnlock) {
String sql = "insert into `%s_unlock`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)"; 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()); 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; return result != 0;
} }
@@ -38,9 +55,9 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
if (sequencesUnlock.getSeq() != null) { if (sequencesUnlock.getSeq() != null) {
sql += " and `%s`=?"; sql += " and `%s`=?";
sql = String.format(sql, tableConfig.getSeqColumn()); sql = String.format(sql, tableConfig.getSeqColumn());
return this.jdbcTemplate.update(sql, sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq()) != 0; return this.jdbcTemplate.update(dbAdapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq()) != 0;
} else { } else {
return this.jdbcTemplate.update(sql, sequencesUnlock.getKey(), sequencesUnlock.getType()) != 0; return this.jdbcTemplate.update(dbAdapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType()) != 0;
} }
} }
@@ -48,7 +65,7 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
public List<SequencesUnlock> listAll() { public List<SequencesUnlock> listAll() {
String sql = "select * from `%s_unlock`"; String sql = "select * from `%s_unlock`";
sql = String.format(sql, tableConfig.getTable()); sql = String.format(sql, tableConfig.getTable());
return this.jdbcTemplate.query(sql, rowMapper()); return this.jdbcTemplate.query(dbAdapter(sql), rowMapper());
} }
@Override @Override
@@ -57,15 +74,15 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
if (begin != null && end != null) { if (begin != null && end != null) {
sql = "select * from `%s_unlock` where `%s`>=? and `%s`<=?"; sql = "select * from `%s_unlock` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn()); 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) { } else if (begin != null) {
sql = "select * from `%s_unlock` where `%s`>=?"; sql = "select * from `%s_unlock` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn()); 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) { } else if (end != null) {
sql = "select * from `%s_unlock` where `%s`<=?"; sql = "select * from `%s_unlock` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn()); sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.query(sql, rowMapper(), end); return this.jdbcTemplate.query(dbAdapter(sql), rowMapper(), end);
} else { } else {
return listAll(); return listAll();
} }
@@ -75,7 +92,7 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
public boolean deleteAll() { public boolean deleteAll() {
String sql = "delete from `%s_unlock`"; String sql = "delete from `%s_unlock`";
sql = String.format(sql, tableConfig.getTable()); sql = String.format(sql, tableConfig.getTable());
int result = this.jdbcTemplate.update(sql); int result = this.jdbcTemplate.update(dbAdapter(sql));
return result != 0; return result != 0;
} }
@@ -85,15 +102,15 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
if (begin != null && end != null) { if (begin != null && end != null) {
sql = "delete from `%s_unlock` where `%s`>=? and `%s`<=?"; sql = "delete from `%s_unlock` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn()); 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) { } else if (begin != null) {
sql = "delete from `%s_unlock` where `%s`>=?"; sql = "delete from `%s_unlock` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn()); 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) { } else if (end != null) {
sql = "delete from `%s_unlock` where `%s`<=?"; sql = "delete from `%s_unlock` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn()); sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, end) != 0; return this.jdbcTemplate.update(dbAdapter(sql), end) != 0;
} else { } else {
return deleteAll(); return deleteAll();
} }
@@ -101,22 +118,7 @@ public class SequencesUnlockDaoImpl implements SequencesUnlockDao {
@Override @Override
public void createTable() { public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s_unlock` ( " + this.createTableByFile("create_table_sequences_unlock.sql");
" `%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);
} }
private RowMapper<SequencesUnlock> rowMapper() { 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.config.TableConfig;
import com.yanghuanglin.seq.dao.SequencesUnusedDao; import com.yanghuanglin.seq.dao.SequencesUnusedDao;
import com.yanghuanglin.seq.enums.DbType;
import com.yanghuanglin.seq.po.SequencesUnused; import com.yanghuanglin.seq.po.SequencesUnused;
import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.BatchPreparedStatementSetter;
@@ -18,14 +19,29 @@ import java.util.List;
* @author yanghuanglin * @author yanghuanglin
* @since 2022/1/28 * @since 2022/1/28
*/ */
@SuppressWarnings("SqlResolve") @SuppressWarnings({"SqlResolve", "SqlSourceToSinkFlow"})
public class SequencesUnusedDaoImpl implements SequencesUnusedDao { public class SequencesUnusedDaoImpl extends SequencesBase implements SequencesUnusedDao {
private final JdbcTemplate jdbcTemplate;
private final TableConfig tableConfig;
public SequencesUnusedDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig) { public SequencesUnusedDaoImpl(JdbcTemplate jdbcTemplate, TableConfig tableConfig, DbType dbType) {
this.jdbcTemplate = jdbcTemplate; super(jdbcTemplate, tableConfig, dbType);
this.tableConfig = tableConfig; }
@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 @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"; 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()); sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn());
try { 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) { } catch (EmptyResultDataAccessException ignored) {
return null; return null;
} }
@@ -44,7 +60,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
try { try {
String sql = "select * from `%s_unused` where `%s`=? and `%s`=? order by `%s` desc limit 0,1"; 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()); 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) { } catch (EmptyResultDataAccessException ignored) {
return null; return null;
} }
@@ -54,7 +70,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
public boolean delete(SequencesUnused sequencesUnused) { public boolean delete(SequencesUnused sequencesUnused) {
String sql = "delete from `%s_unused` where `%s`=? and `%s`=? and `%s`=?"; String sql = "delete from `%s_unused` where `%s`=? and `%s`=? and `%s`=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getKeyColumn(), tableConfig.getTypeColumn(), tableConfig.getSeqColumn()); 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; return result != 0;
} }
@@ -62,7 +78,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
public boolean save(SequencesUnused sequencesUnused) { public boolean save(SequencesUnused sequencesUnused) {
String sql = "insert into `%s_unused`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)"; 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()); 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; return result != 0;
} }
@@ -70,7 +86,7 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
public boolean saveBatch(List<SequencesUnused> sequencesUnusedList) { public boolean saveBatch(List<SequencesUnused> sequencesUnusedList) {
String sql = "insert into `%s_unused`(`%s`,`%s`,`%s`,`%s`) values(?,?,?,?)"; 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()); 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 @Override
public void setValues(PreparedStatement ps, int i) throws SQLException { public void setValues(PreparedStatement ps, int i) throws SQLException {
SequencesUnused sequencesUnused = sequencesUnusedList.get(i); SequencesUnused sequencesUnused = sequencesUnusedList.get(i);
@@ -90,29 +106,14 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
@Override @Override
public void createTable() { public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS `%s_unused` ( " + this.createTableByFile("create_table_sequences_unused.sql");
" `%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);
} }
@Override @Override
public boolean deleteAll() { public boolean deleteAll() {
String sql = "delete from `%s_unused`"; String sql = "delete from `%s_unused`";
sql = String.format(sql, tableConfig.getTable()); sql = String.format(sql, tableConfig.getTable());
int result = this.jdbcTemplate.update(sql); int result = this.jdbcTemplate.update(dbAdapter(sql));
return result != 0; return result != 0;
} }
@@ -122,15 +123,15 @@ public class SequencesUnusedDaoImpl implements SequencesUnusedDao {
if (begin != null && end != null) { if (begin != null && end != null) {
sql = "delete from `%s_unused` where `%s`>=? and `%s`<=?"; sql = "delete from `%s_unused` where `%s`>=? and `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn(), tableConfig.getCreateTimeColumn()); 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) { } else if (begin != null) {
sql = "delete from `%s_unused` where `%s`>=?"; sql = "delete from `%s_unused` where `%s`>=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn()); 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) { } else if (end != null) {
sql = "delete from `%s_unused` where `%s`<=?"; sql = "delete from `%s_unused` where `%s`<=?";
sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn()); sql = String.format(sql, tableConfig.getTable(), tableConfig.getCreateTimeColumn());
return this.jdbcTemplate.update(sql, end) != 0; return this.jdbcTemplate.update(dbAdapter(sql), end) != 0;
} else { } else {
return deleteAll(); 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#"), DAY("#day#"),
/**
* 序号格式字符中的固定字符串
*/
FIX("#fix#"),
/** /**
* 序号格式字符中的格式化后的序号 * 序号格式字符中的格式化后的序号
*/ */

View File

@@ -78,7 +78,7 @@ public interface Generator {
/** /**
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性 * 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串,其最小长度通过{@link BaseConfig#getMinLength()}设定。实际上只会用到{@link Sequences#getSeq()}属性
* <p/> * <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 sequences 生成的序号对象
* @param pattern 格式 * @param pattern 格式
@@ -89,7 +89,7 @@ public interface Generator {
/** /**
* 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性 * 将{@link #generate(String, String, Boolean)}得到的序号对象格式化为补零后的序号字符串。实际上只会用到{@link Sequences#getSeq()}属性
* <p/> * <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 sequences 生成的序号对象
* @param minLength 序号数字最小长度 * @param minLength 序号数字最小长度
@@ -101,7 +101,7 @@ public interface Generator {
/** /**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零 * 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/> * <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/> * <p/>
* seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下 * seq为1pattern为#year##month##day#6#seq#则会格式化为2022013061。此序号含义如下
* <p/> * <p/>
@@ -116,7 +116,7 @@ public interface Generator {
/** /**
* 将生成的序号对象格式化为指定格式 * 将生成的序号对象格式化为指定格式
* <p/> * <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/> * <p/>
* seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下 * seq为1minLength为4pattern为#year##month##day#6#seq#则会格式化为2022013060001。此序号含义如下
* <p/> * <p/>
@@ -132,44 +132,64 @@ public interface Generator {
/** /**
* 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零 * 将生成的序号对象格式化为指定格式,格式化后字符串最小长度为{@link BaseConfig#getMinLength()},不足则补零
* <p/> * <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/> * <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下 * seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013061。此序号含义如下
* <p/> * <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零] * 序号格式:[年][月][日][固定6开头][序号1最小位数为{@link BaseConfig#getMinLength()}设置默认为1不足则补零]
* *
* @param seq 需要格式化的序号 * @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头 * @param fix 序号中的固定字符串
* @param pattern 序号格式 * @param pattern 序号格式
* @return 格式化后的序号字符串 * @return 格式化后的序号字符串
*/ */
String format(Long seq, String start, String pattern); String format(Long seq, String fix, String pattern);
/** /**
* 将生成的序号对象格式化为指定格式 * 将生成的序号对象格式化为指定格式
* <p/> * <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/> * <p/>
* seq为1,start为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下 * seq为1,fix为6minLength为4pattern为#year##month##day##seq#则会格式化为2022013060001。此序号含义如下
* <p/> * <p/>
* 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零] * 序号格式:[年][月][日][固定6开头][序号1最小位数为4位不足4位则补零]
* *
* @param seq 需要格式化的序号 * @param seq 需要格式化的序号
* @param start 序号格式化后以什么字符串开头 * @param fix 序号中的固定字符串
* @param minLength 序号最小长度,不足的会补零 * @param minLength 序号最小长度,不足的会补零
* @param pattern 序号格式 * @param pattern 序号格式
* @return 格式化后的序号字符串 * @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/> * <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/> * <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/> * <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/> * <p/>
* 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()} * 例如SNT序号每年都从1开始则key应该是类似SNT2021、SNT2022这种格式而在配置中该序号的代码只是SNT但是由于每年都要从1开始所有应该每年有一个key这个key就为SNT+年份,而这个年份就是此处解析后返回的对象中的{@link Sequences#getYear()}
* <p/> * <p/>
@@ -181,6 +201,34 @@ public interface Generator {
*/ */
Sequences parse(String formatted, String pattern); 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/> * <p/>
@@ -204,6 +252,14 @@ public interface Generator {
*/ */
boolean lock(Sequences sequences, boolean ignoreSeq); boolean lock(Sequences sequences, boolean ignoreSeq);
/**
* 将序号设为未使用
*
* @param sequences 需要设为未使用的序号
* @return 设置结果
*/
boolean unused(Sequences sequences);
/** /**
* 释放所有未使用的序号 * 释放所有未使用的序号
* <p/> * <p/>
@@ -275,4 +331,9 @@ public interface Generator {
* @param end 结束时间 * @param end 结束时间
*/ */
void clearBefore(Date 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.*; import static com.yanghuanglin.seq.enums.FormatPlaceholder.*;
@SuppressWarnings("CallToPrintStackTrace")
public class SequencesGenerator implements Generator { public class SequencesGenerator implements Generator {
private final TransactionTemplate transactionTemplate; private final TransactionTemplate transactionTemplate;
private final SequencesDao sequencesDao; private final SequencesDao sequencesDao;
@@ -57,12 +58,16 @@ public class SequencesGenerator implements Generator {
private synchronized void createTable(Boolean autoCreate) { private synchronized void createTable(Boolean autoCreate) {
if (!autoCreate) if (!autoCreate)
return; return;
this.createTable();
}
@Override
public synchronized void createTable() {
this.sequencesDao.createTable(); this.sequencesDao.createTable();
this.sequencesUnusedDao.createTable(); this.sequencesUnusedDao.createTable();
this.sequencesUnlockDao.createTable(); this.sequencesUnlockDao.createTable();
} }
@Override @Override
public boolean containSeq(String pattern) { public boolean containSeq(String pattern) {
return StringUtils.hasLength(pattern) && pattern.contains(SEQ.getPlaceholder()); return StringUtils.hasLength(pattern) && pattern.contains(SEQ.getPlaceholder());
@@ -85,7 +90,11 @@ public class SequencesGenerator implements Generator {
//根据传入的key和type新生成查询条件对象 //根据传入的key和type新生成查询条件对象
Sequences condition = new Sequences(key, type); Sequences condition = new Sequences(key, type);
if (!withOutSeq) { if (Boolean.TRUE.equals(withOutSeq)) {
//不包含序号
condition.setWithOutSeq(true);
return condition;
} else {
//不是不包含序号的序号对象(有可能格式中只配置了#year##month##day#,序号就不用自增,也不用入库,直接返回即可) //不是不包含序号的序号对象(有可能格式中只配置了#year##month##day#,序号就不用自增,也不用入库,直接返回即可)
//找到正在使用的最大序号 //找到正在使用的最大序号
Sequences sequences = sequencesDao.find(condition); Sequences sequences = sequencesDao.find(condition);
@@ -119,9 +128,6 @@ public class SequencesGenerator implements Generator {
} }
sequences.setWithOutSeq(false); sequences.setWithOutSeq(false);
return result ? sequences : null; return result ? sequences : null;
} else {
condition.setWithOutSeq(true);
return condition;
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@@ -170,30 +176,48 @@ public class SequencesGenerator implements Generator {
} }
@Override @Override
public String format(Long seq, String start, String pattern) { public String format(Long seq, String fix, String pattern) {
return format(seq, start, minLength, pattern); return format(seq, fix, minLength, pattern);
} }
@Override @Override
public String format(Long seq, String start, Integer minLength, String pattern) { public String format(Long seq, String fix, Integer minLength, String pattern) {
if (start == null) return format(seq, fix, minLength, pattern, null, null, null);
start = ""; }
String seqString = start + new Sequences(seq).format(minLength);
@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(); Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR); if (year == null)
int month = calendar.get(Calendar.MONTH) + 1; year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DAY_OF_MONTH); 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(YEAR.getPlaceholder(), String.valueOf(year));
pattern = pattern.replaceAll(MONTH.getPlaceholder(), monthZeroFilling ? String.format("%02d", month) : String.valueOf(month)); 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(DAY.getPlaceholder(), dayZeroFilling ? String.format("%02d", day) : String.valueOf(day));
pattern = pattern.replaceAll(FIX.getPlaceholder(), fix);
pattern = pattern.replaceAll(SEQ.getPlaceholder(), seqString); pattern = pattern.replaceAll(SEQ.getPlaceholder(), seqString);
return pattern; return pattern;
} }
@Override @Override
public Sequences parse(String formatted, String pattern) { 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); String[] split = pattern.split(splitRegString);
@@ -203,23 +227,25 @@ public class SequencesGenerator implements Generator {
formatted = formatted.replace(splitString, ""); formatted = formatted.replace(splitString, "");
} }
//年、月、日的数字匹配正则规则 //年、月、日、固定字符串 匹配正则规则
String yearRegStr = "\\d{4}"; String yearRegStr = "\\d{4}";
String monthRegStr = "\\d{2}"; String monthRegStr = "\\d{2}";
String dayRegStr = "\\d{2}"; String dayRegStr = "\\d{2}";
String fixRegStr = (fixLength == null || fixLength == 0) ? null : ".{" + fixLength + "}";
//将序号格式分隔特殊符号字符串转为正则匹配规则 //将序号格式分隔特殊符号字符串转为正则匹配规则
Pattern seqPattern = Pattern.compile(splitRegString); Pattern seqPattern = Pattern.compile(splitRegString);
//对序号格式进行匹配 //对序号格式进行匹配
Matcher matcher = seqPattern.matcher(pattern); Matcher matcher = seqPattern.matcher(pattern);
//将年、月、日匹配规则字符串转为正则匹配规则 //将年、月、日、固定字符串 匹配规则字符串转为正则匹配规则
Pattern yearPattern = Pattern.compile(yearRegStr); Pattern yearPattern = Pattern.compile(yearRegStr);
Pattern monthPattern = Pattern.compile(monthRegStr); Pattern monthPattern = Pattern.compile(monthRegStr);
Pattern dayPattern = Pattern.compile(dayRegStr); 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()) { while (matcher.find()) {
String group = matcher.group(); String group = matcher.group();
@@ -233,7 +259,7 @@ public class SequencesGenerator implements Generator {
if (yearMatcher.find()) { if (yearMatcher.find()) {
year = yearMatcher.group(); year = yearMatcher.group();
} }
formatted = formatted.replaceFirst(yearRegStr, ""); formatted = formatted.replaceFirst(yearPattern.pattern(), "");
break; break;
case MONTH: case MONTH:
//若分组为月份分组则将月份正则匹配到的字符串赋值给month同时把格式化后的序号字符串中对应月的字符串替换为空字符串 //若分组为月份分组则将月份正则匹配到的字符串赋值给month同时把格式化后的序号字符串中对应月的字符串替换为空字符串
@@ -241,7 +267,7 @@ public class SequencesGenerator implements Generator {
if (monthMatcher.find()) { if (monthMatcher.find()) {
month = monthMatcher.group(); month = monthMatcher.group();
} }
formatted = formatted.replaceFirst(monthRegStr, ""); formatted = formatted.replaceFirst(monthPattern.pattern(), "");
break; break;
case DAY: case DAY:
//若分组为日期分组则将日期正则匹配到的字符串赋值给day同时把格式化后的序号字符串中对应日期的字符串替换为空字符串 //若分组为日期分组则将日期正则匹配到的字符串赋值给day同时把格式化后的序号字符串中对应日期的字符串替换为空字符串
@@ -249,7 +275,17 @@ public class SequencesGenerator implements Generator {
if (dayMatcher.find()) { if (dayMatcher.find()) {
day = dayMatcher.group(); 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; break;
} }
} }
@@ -262,6 +298,7 @@ public class SequencesGenerator implements Generator {
sequences.setYear(StringUtils.hasLength(year) ? Integer.valueOf(year) : null); sequences.setYear(StringUtils.hasLength(year) ? Integer.valueOf(year) : null);
sequences.setMonth(StringUtils.hasLength(month) ? Integer.valueOf(month) : null); sequences.setMonth(StringUtils.hasLength(month) ? Integer.valueOf(month) : null);
sequences.setDay(StringUtils.hasLength(day) ? Integer.valueOf(day) : 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.setSeq(StringUtils.hasLength(seq) ? Long.parseLong(seq) : 0L);
sequences.setWithOutSeq(!StringUtils.hasLength(seq)); sequences.setWithOutSeq(!StringUtils.hasLength(seq));
sequences.setType(type); sequences.setType(type);
@@ -270,10 +307,30 @@ public class SequencesGenerator implements Generator {
} }
@Override @Override
public synchronized boolean lock(Sequences sequences) { public boolean locked(Sequences sequences) {
if (sequences == null || sequences.getWithOutSeq()) if (sequences == null || Boolean.TRUE.equals(sequences.getWithOutSeq()))
return true; return true;
SequencesUnlock condition = new SequencesUnlock(sequences); SequencesUnlock condition = new SequencesUnlock(sequences);
//将使用中表的对应数据删除,空闲表中数据在生成时会删除,因此这里不需要处理该表
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 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 -> { return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
try { try {
@@ -290,7 +347,7 @@ public class SequencesGenerator implements Generator {
public synchronized boolean lock(Sequences sequences, boolean ignoreSeq) { public synchronized boolean lock(Sequences sequences, boolean ignoreSeq) {
if (!ignoreSeq) if (!ignoreSeq)
return lock(sequences); return lock(sequences);
if (sequences == null || sequences.getWithOutSeq()) if (sequences == null || Boolean.TRUE.equals(sequences.getWithOutSeq()))
return true; return true;
SequencesUnlock condition = new SequencesUnlock(sequences); SequencesUnlock condition = new SequencesUnlock(sequences);
condition.setSeq(null); condition.setSeq(null);
@@ -306,6 +363,24 @@ public class SequencesGenerator implements Generator {
})); }));
} }
@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 @Override
public synchronized boolean release() { public synchronized boolean release() {
//列出所有使用中表存在的序号 //列出所有使用中表存在的序号

View File

@@ -2,6 +2,8 @@ package com.yanghuanglin.seq.po;
import com.yanghuanglin.seq.config.BaseConfig; import com.yanghuanglin.seq.config.BaseConfig;
import java.util.Date;
/** /**
* 当前序号 * 当前序号
* *
@@ -24,6 +26,11 @@ public class Sequences {
*/ */
protected Long seq = 0L; protected Long seq = 0L;
/**
* 最后使用时间
*/
private Date updateTime;
/** /**
* 临时字段序号对应的年份如2022年如果能获取到的话 * 临时字段序号对应的年份如2022年如果能获取到的话
* 该字段仅用于解析序号字符串时解析出对应年份用于合成key序号对应的key为SNT+年份,返回的为其年份) * 该字段仅用于解析序号字符串时解析出对应年份用于合成key序号对应的key为SNT+年份,返回的为其年份)
@@ -42,6 +49,12 @@ public class Sequences {
*/ */
private transient Integer day; private transient Integer day;
/**
* 临时字段序号对应的固定字符串A1
* 该字段仅用于解析序号字符串时解析出对应固定字符用于合成key序号对应的key为SNT+年份+月份+日期+固定字符串,返回的为其固定字符串)
*/
private transient String fix;
/** /**
* 临时字段,表示序号对象不包含序号 * 临时字段,表示序号对象不包含序号
*/ */
@@ -95,6 +108,14 @@ public class Sequences {
this.seq = seq; this.seq = seq;
} }
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getYear() { public Integer getYear() {
return year; return year;
} }
@@ -119,6 +140,14 @@ public class Sequences {
this.day = day; this.day = day;
} }
public String getFix() {
return fix;
}
public void setFix(String fix) {
this.fix = fix;
}
public Boolean getWithOutSeq() { public Boolean getWithOutSeq() {
return withOutSeq; return withOutSeq;
} }
@@ -166,9 +195,11 @@ public class Sequences {
"key='" + key + '\'' + "key='" + key + '\'' +
", type='" + type + '\'' + ", type='" + type + '\'' +
", seq=" + seq + ", seq=" + seq +
", updateTime=" + updateTime +
", year=" + year + ", year=" + year +
", month=" + month + ", month=" + month +
", day=" + day + ", day=" + day +
", fix='" + fix + '\'' +
", withOutSeq=" + withOutSeq + ", 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,15 +1,16 @@
import com.kingbase8.ds.KBSimpleDataSource;
import com.mysql.cj.jdbc.MysqlDataSource; import com.mysql.cj.jdbc.MysqlDataSource;
import com.yanghuanglin.seq.config.BaseConfig;
import com.yanghuanglin.seq.config.GeneratorConfig; import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.config.TableConfig; import com.yanghuanglin.seq.config.TableConfig;
import com.yanghuanglin.seq.generator.Generator; import com.yanghuanglin.seq.generator.Generator;
import com.yanghuanglin.seq.generator.impl.SequencesGenerator; import com.yanghuanglin.seq.generator.impl.SequencesGenerator;
import com.yanghuanglin.seq.po.Sequences; import com.yanghuanglin.seq.po.Sequences;
import dm.jdbc.driver.DmdbDataSource;
import org.junit.Test; import org.junit.Test;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import javax.sql.DataSource;
import java.sql.DatabaseMetaData;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
@@ -21,15 +22,14 @@ import java.util.concurrent.TimeUnit;
* @since 2022/1/28 * @since 2022/1/28
*/ */
public class SeqTest { public class SeqTest {
private static final MysqlDataSource dataSource = new MysqlDataSource(); private static final DataSource dataSource;
private static final Generator generator; private static final Generator generator;
static { static {
dataSource.setURL("jdbc:mysql://127.0.0.1:3306/sequence"); dataSource = dm();
dataSource.setUser("root");
dataSource.setPassword("root");
GeneratorConfig generatorConfig = new GeneratorConfig(dataSource); GeneratorConfig generatorConfig = new GeneratorConfig(dataSource);
System.out.println("DbType: " + generatorConfig.getDbType());
TableConfig tableConfig = new TableConfig(); TableConfig tableConfig = new TableConfig();
tableConfig.setTable("sequences"); tableConfig.setTable("sequences");
@@ -43,6 +43,43 @@ public class SeqTest {
generator = new SequencesGenerator(generatorConfig); 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 @Test
public void generateTest() { public void generateTest() {
//释放未锁定序列号 //释放未锁定序列号
@@ -51,12 +88,17 @@ public class SeqTest {
Set<String> set = new HashSet<>(); Set<String> set = new HashSet<>();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100)); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(100));
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
final int finalI = i;
threadPoolExecutor.execute(() -> { threadPoolExecutor.execute(() -> {
Sequences sequences = generator.generate("SNT", "MISSION"); Sequences sequences = generator.generate("SNT", "MISSION");
String formattedSeq = generator.format(sequences.getSeq(), "处〔#year#10801#seq#"); String pattern = "处〔#year##fix##seq#";
String fix = "10801" + finalI;
String formattedSeq = generator.format(sequences.getSeq(), fix, pattern);
generator.lock(sequences); generator.lock(sequences);
set.add(formattedSeq); set.add(formattedSeq);
System.out.println(formattedSeq); System.out.println(formattedSeq);
Sequences parse = generator.parse(formattedSeq, pattern, fix.length());
System.out.println(parse);
}); });
} }
threadPoolExecutor.shutdown(); threadPoolExecutor.shutdown();
@@ -80,10 +122,11 @@ public class SeqTest {
@Test @Test
public void parseTest() { public void parseTest() {
String seqPattern = "ZZF#year##month##seq#"; String seqPattern = "ZZF#year##month##fix##seq#";
String formatted = "ZZF20220200008"; String formatted = "ZZF202202A18";
Sequences sequences = generator.parse(formatted, seqPattern); //A1视为固定字符串其长度为2
Sequences sequences = generator.parse(formatted, seqPattern, 2);
String key = "zzfCode" + sequences.getYear(); String key = "zzfCode" + sequences.getYear();
@@ -91,4 +134,35 @@ public class SeqTest {
sequences.setType("MISSION"); sequences.setType("MISSION");
System.out.println(sequences); 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);
}
} }