新增 支持pgsql、kingbasees、mysql三种数据库

This commit is contained in:
2024-05-30 10:39:09 +08:00
parent 9104af2923
commit 670cd52c40
20 changed files with 332 additions and 98 deletions

32
pom.xml
View File

@@ -4,22 +4,35 @@
<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.9.2</version> <version>1.10.0</version>
<name>seq</name> <name>seq</name>
<description>seq</description> <description>seq</description>
<properties> <properties>
<java.version>1.9</java.version> <java.version>1.8</java.version>
</properties> </properties>
<dependencies> <dependencies>
<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>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@@ -30,6 +43,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 +63,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,9 @@
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.SQLException;
/** /**
* 生成器配置 * 生成器配置
@@ -49,6 +52,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 +129,20 @@ 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 {
String productName = this.dataSource.getConnection().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

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

View File

@@ -40,5 +40,8 @@ public interface SequencesUnlockDao {
*/ */
boolean deleteByDate(Date begin, Date end); boolean deleteByDate(Date begin, Date end);
/**
* 创建表
*/
void createTable(); void createTable();
} }

View File

@@ -36,6 +36,9 @@ public interface SequencesUnusedDao {
*/ */
boolean saveBatch(List<SequencesUnused> sequencesUnusedList); boolean saveBatch(List<SequencesUnused> sequencesUnusedList);
/**
* 创建表
*/
void createTable(); void createTable();
/** /**

View File

@@ -0,0 +1,87 @@
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 javax.sql.DataSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
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 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));
databasePopulator.execute(dataSource);
} catch (IOException e) {
System.err.println("执行SQL文件" + fileName + "失败");
}
}
/**
* 根据数据库类型简单处理sql语句
*
* @param sqlString sql语句
* @return 处理后的语句
*/
protected String adapter(String sqlString) {
switch (dbType) {
case MySQL:
break;
case PostgreSQL:
case KingbaseES:
sqlString = sqlString.replaceAll("`(.+?)`", "\"$1\"");
break;
}
return sqlString;
}
}

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.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;
@@ -12,13 +13,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
* @since 2022/1/28 * @since 2022/1/28
*/ */
@SuppressWarnings("SqlResolve") @SuppressWarnings("SqlResolve")
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,7 +24,7 @@ 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(adapter(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()));
@@ -42,7 +40,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(adapter(sql), sequences.getKey(), sequences.getType(), sequences.getSeq());
return result != 0; return result != 0;
} }
@@ -50,24 +48,12 @@ 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(adapter(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 '序号英文名称'," +
" `%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);
} }
} }

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.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.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
@@ -14,20 +15,17 @@ import java.util.List;
* @since 2022/1/28 * @since 2022/1/28
*/ */
@SuppressWarnings("SqlResolve") @SuppressWarnings("SqlResolve")
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 @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(adapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq(), sequencesUnlock.getCreateTime());
return result != 0; return result != 0;
} }
@@ -38,9 +36,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(adapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType(), sequencesUnlock.getSeq()) != 0;
} else { } else {
return this.jdbcTemplate.update(sql, sequencesUnlock.getKey(), sequencesUnlock.getType()) != 0; return this.jdbcTemplate.update(adapter(sql), sequencesUnlock.getKey(), sequencesUnlock.getType()) != 0;
} }
} }
@@ -48,7 +46,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(adapter(sql), rowMapper());
} }
@Override @Override
@@ -57,15 +55,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(adapter(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(adapter(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(adapter(sql), rowMapper(), end);
} else { } else {
return listAll(); return listAll();
} }
@@ -75,7 +73,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(adapter(sql));
return result != 0; return result != 0;
} }
@@ -85,15 +83,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(adapter(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(adapter(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(adapter(sql), end) != 0;
} else { } else {
return deleteAll(); return deleteAll();
} }
@@ -101,22 +99,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;
@@ -19,13 +20,10 @@ import java.util.List;
* @since 2022/1/28 * @since 2022/1/28
*/ */
@SuppressWarnings("SqlResolve") @SuppressWarnings("SqlResolve")
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 @Override
@@ -33,7 +31,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(adapter(sql), rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
} catch (EmptyResultDataAccessException ignored) { } catch (EmptyResultDataAccessException ignored) {
return null; return null;
} }
@@ -44,7 +42,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(adapter(sql), rowMapper(), sequencesUnused.getKey(), sequencesUnused.getType());
} catch (EmptyResultDataAccessException ignored) { } catch (EmptyResultDataAccessException ignored) {
return null; return null;
} }
@@ -54,7 +52,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(adapter(sql), sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq());
return result != 0; return result != 0;
} }
@@ -62,7 +60,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(adapter(sql), sequencesUnused.getKey(), sequencesUnused.getType(), sequencesUnused.getSeq(), sequencesUnused.getCreateTime());
return result != 0; return result != 0;
} }
@@ -70,7 +68,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(adapter(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 +88,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(adapter(sql));
return result != 0; return result != 0;
} }
@@ -122,15 +105,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(adapter(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(adapter(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(adapter(sql), end) != 0;
} else { } else {
return deleteAll(); return deleteAll();
} }

View File

@@ -0,0 +1,35 @@
package com.yanghuanglin.seq.enums;
public enum DbType {
//MySQL数据库
MySQL("mysql"),
//人大金仓数据库
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)) {
return value;
}
}
throw new RuntimeException("不支持的数据库类型");
}
}

View File

@@ -315,4 +315,9 @@ public interface Generator {
* @param end 结束时间 * @param end 结束时间
*/ */
void clearBefore(Date end); void clearBefore(Date end);
/**
* 创建表
*/
void createTable();
} }

View File

@@ -57,12 +57,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());

View File

@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS `sequences`
(
`key` VARCHAR(64) NOT NULL COMMENT '序号英文名称',
`type` VARCHAR(64) NOT NULL COMMENT '序号类型',
`seq` BIGINT(20) NOT NULL 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,11 @@
CREATE TABLE IF NOT EXISTS "sequences"
(
"key" VARCHAR(64) NOT NULL,
"type" VARCHAR(64) NOT NULL,
"seq" INT8 NOT NULL,
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 '已使用到的序号';

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,3 +1,4 @@
import com.kingbase8.ds.KBSimpleDataSource;
import com.mysql.cj.jdbc.MysqlDataSource; import com.mysql.cj.jdbc.MysqlDataSource;
import com.yanghuanglin.seq.config.GeneratorConfig; import com.yanghuanglin.seq.config.GeneratorConfig;
import com.yanghuanglin.seq.config.TableConfig; import com.yanghuanglin.seq.config.TableConfig;
@@ -5,7 +6,9 @@ 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 org.junit.Test; import org.junit.Test;
import org.postgresql.ds.PGSimpleDataSource;
import javax.sql.DataSource;
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;
@@ -17,15 +20,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 = pgsql();
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");
@@ -39,6 +41,35 @@ 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;
}
@Test
public void createTable() {
generator.createTable();
}
@Test @Test
public void generateTest() { public void generateTest() {
//释放未锁定序列号 //释放未锁定序列号