From b8e24d42aed5a4edbf64e7d325b8366dad991a74 Mon Sep 17 00:00:00 2001 From: Hideki Sugimoto Date: Mon, 8 Jan 2024 17:40:56 +0900 Subject: [PATCH] =?UTF-8?q?-=20v0.x=E7=B3=BB=E3=81=AE=E4=B8=8D=E5=85=B7?= =?UTF-8?q?=E5=90=88=E5=AF=BE=E5=BF=9C=E3=81=AE=E8=BF=BD=E3=81=84=E3=81=A4?= =?UTF-8?q?=E3=81=8D=20-=20=E3=83=AD=E3=82=B0=E5=87=BA=E5=8A=9B=E3=81=AE?= =?UTF-8?q?=E6=95=B4=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/settings.json | 56 +- .../uroborosql/AbstractResultSetWrapper.java | 11 +- .../jp/co/future/uroborosql/SqlAgentImpl.java | 26 +- .../future/uroborosql/SqlEntityQueryImpl.java | 24 +- .../uroborosql/client/SqlParamUtils.java | 2 +- .../co/future/uroborosql/client/SqlREPL.java | 13 +- .../client/completer/TableNameCompleter.java | 2 +- .../context/ExecutionContextImpl.java | 25 +- .../context/ExecutionContextProviderImpl.java | 32 +- .../coverage/CoberturaCoverageHandler.java | 18 +- .../uroborosql/coverage/CoverageData.java | 23 +- .../html/HtmlReportCoverageHandler.java | 11 +- .../reports/html/SqlCoverageReport.java | 6 +- .../future/uroborosql/dialect/H2Dialect.java | 3 +- .../uroborosql/dialect/MsSqlDialect.java | 3 +- .../uroborosql/dialect/MySqlDialect.java | 3 +- .../uroborosql/dialect/PostgresqlDialect.java | 3 +- .../AbstractSecretColumnEventSubscriber.java | 28 +- .../subscriber/AuditLogEventSubscriber.java | 16 +- .../subscriber/DebugEventSubscriber.java | 37 +- .../subscriber/DumpResultEventSubscriber.java | 13 +- .../expr/spel/SpelExpressionParser.java | 7 +- .../future/uroborosql/mapping/JavaType.java | 14 +- .../uroborosql/mapping/MappingColumn.java | 84 +- .../jp/co/future/uroborosql/node/IfNode.java | 2 +- .../uroborosql/parameter/Parameter.java | 22 +- .../store/SqlResourceManagerImpl.java | 51 +- .../tx/LocalTransactionContext.java | 4 +- .../context/ExecutionContextImplTest.java | 80 +- .../mapping/DefaultEntityHandlerTest.java | 107 ++ .../uroborosql/mapping/MappingColumnTest.java | 1361 +++++++++++++++++ .../uroborosql/mapping/TestEntity4.java | 124 ++ .../uroborosql/mapping/TestEntity5.java | 125 ++ .../testExecuteBatchEvent.txt | 2 +- .../testExecuteQueryEvent.txt | 2 +- .../testExecuteQueryEventCustomParam.txt | 2 +- .../testExecuteUpdateEvent.txt | 2 +- src/test/resources/logback-test.xml | 18 +- 38 files changed, 2160 insertions(+), 202 deletions(-) create mode 100644 src/test/java/jp/co/future/uroborosql/mapping/MappingColumnTest.java create mode 100644 src/test/java/jp/co/future/uroborosql/mapping/TestEntity4.java create mode 100644 src/test/java/jp/co/future/uroborosql/mapping/TestEntity5.java diff --git a/.vscode/settings.json b/.vscode/settings.json index 497c9f01..44a8a0cb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,62 @@ { "cSpell.words": [ + "autocommit", + "Autoincrement", + "batyz", + "batyzyzy", + "batzz", "Choi", + "chrono", + "classpath", + "Cobertura", + "crypted", + "cstmt", + "datasources", + "Decryptor", + "hamcrest", + "Hmmss", + "holdability", + "hoshi", + "iface", + "inactives", + "JCEKS", "jdbc", + "jline", + "jquery", "Miyazaki", - "Sugimoto" + "MSSQL", + "multibyte", + "nextval", + "NOWAIT", + "nparams", + "ognl", + "PKCS", + "rawtypes", + "rsmd", + "Savepoints", + "SCHEM", + "spel", + "springframework", + "sqlcov", + "sqlname", + "sqls", + "stupidtable", + "subparameter", + "Sugimoto", + "SYSPROP", + "thead", + "timestamptz", + "timetz", + "transactionisolation", + "uncapitalize", + "unmanaged", + "unmatch", + "UPDLOCK", + "Uroboro", + "uroborosql", + "vals", + "yzbat", + "yzyzybat", + "zzbat" ] } \ No newline at end of file diff --git a/src/main/java/jp/co/future/uroborosql/AbstractResultSetWrapper.java b/src/main/java/jp/co/future/uroborosql/AbstractResultSetWrapper.java index 28b19f2f..14fd4e1f 100644 --- a/src/main/java/jp/co/future/uroborosql/AbstractResultSetWrapper.java +++ b/src/main/java/jp/co/future/uroborosql/AbstractResultSetWrapper.java @@ -51,12 +51,12 @@ public AbstractResultSetWrapper(final ResultSet wrapped) { * * @see java.sql.Wrapper#unwrap(java.lang.Class) */ + @SuppressWarnings("unchecked") @Override public T unwrap(final Class iface) throws SQLException { - if (iface != null && this.getClass().isAssignableFrom(iface)) { - return iface.cast(this); + if (iface != null && iface.isAssignableFrom(this.getClass())) { + return (T) this; } - return wrapped.unwrap(iface); } @@ -67,10 +67,11 @@ public T unwrap(final Class iface) throws SQLException { */ @Override public boolean isWrapperFor(final Class iface) throws SQLException { - if (iface != null && this.getClass().isAssignableFrom(iface)) { + if (iface != null && iface.isAssignableFrom(this.getClass())) { return true; + } else { + return wrapped.isWrapperFor(iface); } - return wrapped.isWrapperFor(iface); } /** diff --git a/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java b/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java index d70b13c0..db1ba28f 100644 --- a/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java +++ b/src/main/java/jp/co/future/uroborosql/SqlAgentImpl.java @@ -174,8 +174,10 @@ public class SqlAgentImpl implements SqlAgent { Thread.currentThread().getContextClassLoader()).getConstructor().newInstance(); COVERAGE_LOG.info("CoverageHandler : {}", sqlCoverageClassName); } catch (Exception ex) { - COVERAGE_LOG.warn("Failed to generate CoverageHandler class. Class:{}, Cause:{}", sqlCoverageClassName, + COVERAGE_LOG.warn("Failed to instantiate CoverageHandler class. Class:{}, Cause:{}", + sqlCoverageClassName, ex.getMessage()); + COVERAGE_LOG.info("Turn off sql coverage due to failure to instantiate CoverageHandler class."); } } @@ -1235,7 +1237,7 @@ public ResultSet query(final ExecutionContext executionContext) throws SQLExcept Instant startTime = null; if (LOG.isDebugEnabled()) { - LOG.debug("Execute search SQL."); + LOG.debug("Execute query sql. sqlName: {}", executionContext.getSqlName()); } if (PERFORMANCE_LOG.isInfoEnabled()) { startTime = Instant.now(getSqlConfig().getClock()); @@ -1384,7 +1386,9 @@ public int update(final ExecutionContext executionContext) throws SQLException { // 更新移譲処理の指定がある場合は移譲処理を実行し結果を返却 if (executionContext.getUpdateDelegate() != null) { MDC.remove(SUPPRESS_PARAMETER_LOG_OUTPUT); - LOG.debug("Performs update delegate of update process"); + if (LOG.isInfoEnabled()) { + LOG.info("Performs update delegate of update process."); + } return executionContext.getUpdateDelegate().apply(executionContext); } @@ -1396,7 +1400,7 @@ public int update(final ExecutionContext executionContext) throws SQLException { executionContext.bindParams(stmt); if (LOG.isDebugEnabled()) { - LOG.debug("Execute update SQL."); + LOG.debug("Execute update sql. sqlName: {}", executionContext.getSqlName()); } if (PERFORMANCE_LOG.isInfoEnabled()) { startTime = Instant.now(getSqlConfig().getClock()); @@ -1509,7 +1513,9 @@ public int[] batch(final ExecutionContext executionContext) throws SQLException // 更新移譲処理の指定がある場合は移譲処理を実行し結果を返却 if (executionContext.getUpdateDelegate() != null) { MDC.remove(SUPPRESS_PARAMETER_LOG_OUTPUT); - LOG.debug("Performs update delegate of batch process"); + if (LOG.isInfoEnabled()) { + LOG.info("Performs update delegate of batch process."); + } return new int[] { executionContext.getUpdateDelegate().apply(executionContext) }; } @@ -1521,7 +1527,7 @@ public int[] batch(final ExecutionContext executionContext) throws SQLException executionContext.bindBatchParams(stmt); if (LOG.isDebugEnabled()) { - LOG.debug("Execute batch process."); + LOG.debug("Execute batch sql. sqlName: {}", executionContext.getSqlName()); } if (PERFORMANCE_LOG.isInfoEnabled()) { startTime = Instant.now(getSqlConfig().getClock()); @@ -1645,7 +1651,7 @@ public Map procedure(final ExecutionContext executionContext) th executionContext.bindParams(callableStatement); if (LOG.isDebugEnabled()) { - LOG.debug("Execute stored procedure."); + LOG.debug("Execute stored procedure. sqlName: {}", executionContext.getSqlName()); } if (PERFORMANCE_LOG.isInfoEnabled()) { startTime = Instant.now(getSqlConfig().getClock()); @@ -1788,7 +1794,9 @@ && getSqlConfig().getEventListenerHolder().hasBeforeParseSqlListener()) { // SQLカバレッジ用のログを出力する var coverageData = new CoverageData(sqlName, originalSql, contextTransformer.getPassedRoute()); - COVERAGE_LOG.info("{}", coverageData); + if (COVERAGE_LOG.isDebugEnabled()) { + COVERAGE_LOG.debug("coverage data: {}", coverageData); + } coverageHandlerRef.get().accept(coverageData); } @@ -1837,7 +1845,7 @@ private void handleException(final ExecutionContext executionContext, final SQLE cause = cause.getNextException(); } - if (LOG.isErrorEnabled() && outputExceptionLog) { + if (outputExceptionLog && LOG.isErrorEnabled()) { var builder = new StringBuilder(); builder.append(System.lineSeparator()).append("Exception occurred in SQL execution.") .append(System.lineSeparator()); diff --git a/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java b/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java index c1c29754..d3903060 100644 --- a/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java +++ b/src/main/java/jp/co/future/uroborosql/SqlEntityQueryImpl.java @@ -250,13 +250,7 @@ public long count(final String col) { public T sum(final String col) { var camelColumnName = CaseFormat.CAMEL_CASE.convert(col); var mappingColumn = MappingUtils.getMappingColumn(context().getSchema(), entityType, camelColumnName); - Class rawType = mappingColumn.getJavaType().getRawType(); - if (!(short.class.equals(rawType) || - int.class.equals(rawType) || - long.class.equals(rawType) || - float.class.equals(rawType) || - double.class.equals(rawType) || - Number.class.isAssignableFrom(mappingColumn.getJavaType().getRawType()))) { + if (!mappingColumn.isNumber()) { throw new UroborosqlRuntimeException("Column is not of type Number. col=" + camelColumnName); } var column = tableMetadata().getColumn(camelColumnName); @@ -530,7 +524,9 @@ public SqlEntityQuery forUpdateNoWait() { return this; } else if (!agent().getSqlConfig().getSqlAgentProvider().isStrictForUpdateType() && dialect.supportsForUpdate()) { - LOG.warn("'FOR UPDATE NOWAIT' is not supported. Set 'FOR UPDATE' instead."); + if (LOG.isWarnEnabled()) { + LOG.warn("'FOR UPDATE NOWAIT' is not supported. Set 'FOR UPDATE' instead."); + } this.forUpdateType = ForUpdateType.NORMAL; return this; } else { @@ -549,7 +545,9 @@ public SqlEntityQuery forUpdateWait() { return forUpdateWait(agent().getSqlConfig().getSqlAgentProvider().getDefaultForUpdateWaitSeconds()); } else if (!agent().getSqlConfig().getSqlAgentProvider().isStrictForUpdateType() && dialect.supportsForUpdate()) { - LOG.warn("'FOR UPDATE WAIT' is not supported. Set 'FOR UPDATE' instead."); + if (LOG.isWarnEnabled()) { + LOG.warn("'FOR UPDATE WAIT' is not supported. Set 'FOR UPDATE' instead."); + } this.forUpdateType = ForUpdateType.NORMAL; return this; } else { @@ -570,7 +568,9 @@ public SqlEntityQuery forUpdateWait(final int waitSeconds) { return this; } else if (!agent().getSqlConfig().getSqlAgentProvider().isStrictForUpdateType() && dialect.supportsForUpdate()) { - LOG.warn("'FOR UPDATE WAIT' is not supported. Set 'FOR UPDATE' instead."); + if (LOG.isWarnEnabled()) { + LOG.warn("'FOR UPDATE WAIT' is not supported. Set 'FOR UPDATE' instead."); + } this.forUpdateType = ForUpdateType.NORMAL; return this; } else { @@ -588,7 +588,9 @@ public SqlEntityQuery hint(final String hint) { if (dialect.supportsOptimizerHints()) { this.optimizerHints.add(hint); } else { - LOG.warn("Optimizer Hints is not supported."); + if (LOG.isWarnEnabled()) { + LOG.warn("Optimizer Hints is not supported."); + } } return this; } diff --git a/src/main/java/jp/co/future/uroborosql/client/SqlParamUtils.java b/src/main/java/jp/co/future/uroborosql/client/SqlParamUtils.java index b327374f..e95bd87d 100644 --- a/src/main/java/jp/co/future/uroborosql/client/SqlParamUtils.java +++ b/src/main/java/jp/co/future/uroborosql/client/SqlParamUtils.java @@ -57,7 +57,7 @@ private SqlParamUtils() { * @return 入力内容をパラメータに分割した配列 */ public static String[] parseLine(final String line) { - var sb = new StringBuffer(); + var sb = new StringBuilder(); var matcher = PARAM_PAT.matcher(line); while (matcher.find()) { var arrayPart = matcher.group(); diff --git a/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java b/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java index 683c6e59..fe731020 100644 --- a/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java +++ b/src/main/java/jp/co/future/uroborosql/client/SqlREPL.java @@ -83,14 +83,13 @@ public class SqlREPL { */ public static void main(final String... args) { ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.log")).setLevel(Level.INFO); - ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.log.event")).setLevel(Level.INFO); - ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.sql")).setLevel(Level.INFO); - ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.sql.dx")).setLevel(Level.TRACE); + ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.setting")).setLevel(Level.ERROR); + ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.performance")).setLevel(Level.INFO); + ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.event")).setLevel(Level.DEBUG); + ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.repl")).setLevel(Level.INFO); + ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.sql")).setLevel(Level.DEBUG); ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.sql.parser")).setLevel(Level.ERROR); - ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.sql.repl")).setLevel(Level.ERROR); ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.sql.coverage")).setLevel(Level.ERROR); - ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.performance")).setLevel(Level.INFO); - ((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql.setting")).setLevel(Level.ERROR); var propFile = "repl.properties"; if (args.length != 0) { @@ -183,7 +182,7 @@ private void initialize(final Terminal terminal) throws Exception { Arrays.stream(paths.split(";")).forEach(path -> { try { var m = SYSPROP_PAT.matcher(path); - var sb = new StringBuffer(); + var sb = new StringBuilder(); while (m.find()) { var key = m.group(1); var val = System.getProperty(key, null); diff --git a/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java b/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java index 66684e1a..d69e362d 100644 --- a/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java +++ b/src/main/java/jp/co/future/uroborosql/client/completer/TableNameCompleter.java @@ -37,7 +37,7 @@ public TableNameCompleter(final List commands, final ConnectionSupp } /** - * DatabaseMetadateからテーブル名を取得して補完候補とする。 + * DatabaseMetadataからテーブル名を取得して補完候補とする。 * * {@inheritDoc} * diff --git a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java index 06cd37dd..25fca741 100644 --- a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java +++ b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextImpl.java @@ -76,19 +76,18 @@ public boolean contains(final Object o) { } /** where句の直後にくるANDやORを除外するための正規表現 */ - private static final Pattern WHERE_CLAUSE_PATTERN = Pattern - .compile("(?i)(?(^|\\s+)(WHERE\\s+(--.*|/\\*[^(/\\*|\\*/)]+?\\*/\\s*)*\\s*))(AND\\s+|OR\\s+)"); + private static final Pattern WHERE_CLAUSE_PATTERN = Pattern.compile( + "(?i)(?(\\bWHERE\\s+(--.*|/\\*[^(/\\*|\\*/)]+?\\*/\\s*)*\\s*))((AND|OR)\\s+)"); /** 各句の最初に現れるカンマを除去するための正規表現 */ - private static final Pattern REMOVE_FIRST_COMMA_PATTERN = Pattern - .compile( - "(?i)(?((^|\\s+)(SELECT|ORDER\\s+BY|GROUP\\s+BY|SET)\\s+|\\(\\s*)(--.*|/\\*[^(/\\*|\\*/)]+?\\*/\\s*)*\\s*)(,)"); + private static final Pattern REMOVE_FIRST_COMMA_PATTERN = Pattern.compile( + "(?i)(?(\\b(SELECT|ORDER\\s+BY|GROUP\\s+BY|SET)\\s+|\\(\\s*)(--.*|/\\*[^(/\\*|\\*/)]+?\\*/\\s*)*\\s*),"); /** 不要な空白、改行を除去するための正規表現 */ private static final Pattern CLEAR_BLANK_PATTERN = Pattern.compile("(?m)^\\s*(\\r\\n|\\r|\\n)"); - /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log"); + /** SQLロガー */ + private static final Logger SQL_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.sql"); /** SqlConfig. */ private SqlConfig sqlConfig; @@ -235,7 +234,7 @@ public String getExecutableSql() { executableSqlCache = executableSql.toString(); if (executableSqlCache.toUpperCase().contains("WHERE")) { // where句の直後に来るANDやORの除去 - var buff = new StringBuffer(); + var buff = new StringBuilder(); var matcher = WHERE_CLAUSE_PATTERN.matcher(executableSqlCache); while (matcher.find()) { var whereClause = matcher.group("clause"); @@ -245,7 +244,7 @@ public String getExecutableSql() { executableSqlCache = buff.toString(); } // 各句の直後に現れる不要なカンマの除去 - var buff = new StringBuffer(); + var buff = new StringBuilder(); var removeCommaMatcher = REMOVE_FIRST_COMMA_PATTERN.matcher(executableSqlCache); while (removeCommaMatcher.find()) { var clauseWords = removeCommaMatcher.group("keyword"); @@ -927,8 +926,8 @@ public void bindBatchParams(final PreparedStatement preparedStatement) throws SQ bindParams(preparedStatement); preparedStatement.addBatch(); } - if (LOG.isDebugEnabled()) { - LOG.debug("{} items Added for batch process.", batchParameters.size()); + if (SQL_LOG.isDebugEnabled()) { + SQL_LOG.debug("{} items Added for batch process.", batchParameters.size()); } } @@ -959,8 +958,8 @@ public Map getOutParams(final CallableStatement callableStatemen parameterIndex++; } - if (LOG.isDebugEnabled()) { - LOG.debug("Stored procedure out parameter[{}]", out); + if (SQL_LOG.isDebugEnabled()) { + SQL_LOG.debug("Stored procedure out parameter[{}]", out); } return out; } diff --git a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java index 94fcfb32..2a7fdf32 100644 --- a/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java +++ b/src/main/java/jp/co/future/uroborosql/context/ExecutionContextProviderImpl.java @@ -160,13 +160,17 @@ protected void makeConstParamMap(final Map paramMap, var newValue = new Parameter(fieldName, field.get(null)); var prevValue = paramMap.put(fieldName, newValue); if (prevValue != null) { - SETTING_LOG.warn("Duplicate constant name. Constant name:{}, old value:{} destroy.", + if (SETTING_LOG.isWarnEnabled()) { + SETTING_LOG.warn("Duplicate constant name. Constant name:{}, old value:{} destroy.", + fieldName, + prevValue.getValue()); + } + } + if (SETTING_LOG.isInfoEnabled()) { + SETTING_LOG.info("Constant [name:{}, value:{}] added to parameter.", fieldName, - prevValue.getValue()); + newValue.getValue()); } - SETTING_LOG.info("Constant [name:{}, value:{}] added to parameter.", - fieldName, - newValue.getValue()); } } } @@ -205,13 +209,17 @@ protected void makeEnumConstParamMap(final Map paramMap, var newValue = new Parameter(fieldName, value); var prevValue = paramMap.put(fieldName, newValue); if (prevValue != null) { - SETTING_LOG.warn("Duplicate Enum name. Enum name:{}, old value:{} destroy.", + if (SETTING_LOG.isWarnEnabled()) { + SETTING_LOG.warn("Duplicate Enum name. Enum name:{}, old value:{} destroy.", + fieldName, + prevValue.getValue()); + } + } + if (SETTING_LOG.isInfoEnabled()) { + SETTING_LOG.info("Enum [name:{}, value:{}] added to parameter.", fieldName, - prevValue.getValue()); + newValue.getValue()); } - SETTING_LOG.info("Enum [name:{}, value:{}] added to parameter.", - fieldName, - newValue.getValue()); } } @@ -339,7 +347,7 @@ public ExecutionContextProvider removeBindParamMapper(final BindParameterMapper< var paramMap = new HashMap(); for (var packageName : enumConstantPackageNames) { if (StringUtils.isNotBlank(packageName)) { - for (var targetClass : listupEnumClasses(packageName)) { + for (var targetClass : listUpEnumClasses(packageName)) { makeEnumConstParamMap(paramMap, packageName, targetClass); } } @@ -354,7 +362,7 @@ public ExecutionContextProvider removeBindParamMapper(final BindParameterMapper< * @return クラスリスト */ @SuppressWarnings({ "unchecked", "rawtypes" }) - private static Set>> listupEnumClasses(final String packageName) { + private static Set>> listUpEnumClasses(final String packageName) { var resourceName = packageName.replace('.', '/'); var classLoader = Thread.currentThread().getContextClassLoader(); List roots; diff --git a/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java b/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java index 4313c3b7..f160f43c 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/CoberturaCoverageHandler.java @@ -52,7 +52,8 @@ * @author ota */ public class CoberturaCoverageHandler implements CoverageHandler { - protected static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log"); + /** カバレッジロガー. */ + private static final Logger COVERAGE_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.sql.coverage"); /** * カバレッジ数値 line branch セット @@ -91,12 +92,9 @@ private void add(final CoverageSummary o) { * ポイントブランチ情報 */ private static class PointBranch { - @SuppressWarnings("unused") - private final Range range; private final Set status = EnumSet.noneOf(BranchCoverageState.class); private PointBranch(final Range range) { - this.range = range; } private void add(final BranchCoverageState state) { @@ -112,12 +110,9 @@ private int coveredSize() { * 行ブランチ情報 */ private static class LineBranch { - @SuppressWarnings("unused") - private final int rowIndex; private final Map branches = new HashMap<>(); private LineBranch(final int rowIndex) { - this.rowIndex = rowIndex; } private void add(final Range idx, final BranchCoverageState state) { @@ -140,8 +135,6 @@ private int coveredSize() { */ private static class SqlCoverage { private final String name; - @SuppressWarnings("unused") - private final String md5; /** 各行範囲 */ private final List lineRanges; @@ -154,7 +147,6 @@ private SqlCoverage(final String name, final String sql, final String md5, final final int hashIndex) throws IOException { this.name = hashIndex <= 0 ? name : name + "_hash_" + hashIndex; - this.md5 = md5; this.lineRanges = CoverageHandler.parseLineRanges(sql); this.hitLines = new int[lineRanges.stream() .mapToInt(LineRange::getLineIndex) @@ -266,7 +258,7 @@ public synchronized void accept(final CoverageData coverageData) { sqlCoverage = new SqlCoverage(coverageData.getSqlName(), coverageData.getSql(), coverageData.getMd5(), sourcesDirPath, map.size()); } catch (IOException e) { - LOG.error(e.getMessage(), e); + COVERAGE_LOG.error(e.getMessage(), e); return; } map.put(coverageData.getMd5(), sqlCoverage); @@ -281,7 +273,7 @@ public synchronized void onSqlAgentClose() { try { write(); } catch (Exception e) { - LOG.error(e.getMessage(), e); + COVERAGE_LOG.error(e.getMessage(), e); } } @@ -291,7 +283,7 @@ private void init() { try { write(); } catch (Exception e) { - LOG.error(e.getMessage(), e); + COVERAGE_LOG.error(e.getMessage(), e); } })); } diff --git a/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java b/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java index ae4c6d49..05d56a3a 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/CoverageData.java @@ -17,10 +17,19 @@ * @author ota */ public class CoverageData { - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log"); + /** カバレッジロガー. */ + private static final Logger COVERAGE_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.sql.coverage"); + + /** SQL名. */ private final String sqlName; + + /** 変換前SQL. */ private final String sql; + + /** MD5文字列. */ private final String md5; + + /** 分岐情報. */ private final PassedRoute passRoute; /** @@ -57,7 +66,7 @@ private String makeMd5(final String original) { } return builder.toString(); } catch (Exception ex) { - LOG.error(ex.getMessage(), ex); + COVERAGE_LOG.error(ex.getMessage(), ex); } return ""; } @@ -71,7 +80,7 @@ public String toJSON() { var builder = new StringBuilder(); builder.append("{\"sqlName\":"); if (sqlName != null) { - builder.append(sqlName.replaceAll("/", "\\/")); + builder.append(sqlName.replace('/', '/')); } else { builder.append(""); } @@ -82,7 +91,7 @@ public String toJSON() { } /** - * SQL名取得 + * SQL名取得. * * @return SQLファイルのルートからの相対パス(ファイル拡張子なし) */ @@ -91,7 +100,7 @@ public String getSqlName() { } /** - * 変換前SQL取得 + * 変換前SQL取得. * * @return 変換前SQL */ @@ -100,7 +109,7 @@ public String getSql() { } /** - * SQLのMD5取得 + * SQLのMD5取得. * * @return MD5 */ @@ -109,7 +118,7 @@ public String getMd5() { } /** - * 分岐情報取得 + * 分岐情報取得. * * @return 分岐情報 */ diff --git a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java index e654a9b8..9ca7ab9e 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/HtmlReportCoverageHandler.java @@ -42,10 +42,13 @@ * @author ota */ public class HtmlReportCoverageHandler implements CoverageHandler { - /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log"); + /** カバレッジロガー. */ + private static final Logger COVERAGE_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.sql.coverage"); + /** カバレッジ情報. */ private final Map> coverages = new ConcurrentHashMap<>(); + + /** レポートディレクトリパス. */ private final Path reportDirPath; /** @@ -112,7 +115,7 @@ private void writeHtml() { Files.copy(src, Paths.get(this.reportDirPath + "/" + filename), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { - LOG.error(e.getMessage(), e); + COVERAGE_LOG.error(e.getMessage(), e); } }); // write report @@ -129,7 +132,7 @@ private void writeHtml() { writeSuffix(writer); } } catch (IOException e) { - LOG.error(e.getMessage(), e); + COVERAGE_LOG.error(e.getMessage(), e); } } diff --git a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java index 977ff6b5..4c2d2d7e 100644 --- a/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java +++ b/src/main/java/jp/co/future/uroborosql/coverage/reports/html/SqlCoverageReport.java @@ -34,8 +34,8 @@ import jp.co.future.uroborosql.utils.StringUtils; class SqlCoverageReport { - /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log"); + /** カバレッジロガー. */ + private static final Logger COVERAGE_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.sql.coverage"); private final String name; private final String sql; @@ -129,7 +129,7 @@ void writeHtml() { writeSuffix(writer); } } catch (IOException e) { - LOG.error(e.getMessage(), e); + COVERAGE_LOG.error(e.getMessage(), e); } updated = false; } diff --git a/src/main/java/jp/co/future/uroborosql/dialect/H2Dialect.java b/src/main/java/jp/co/future/uroborosql/dialect/H2Dialect.java index 4158696e..2e8aed4d 100644 --- a/src/main/java/jp/co/future/uroborosql/dialect/H2Dialect.java +++ b/src/main/java/jp/co/future/uroborosql/dialect/H2Dialect.java @@ -6,7 +6,6 @@ */ package jp.co.future.uroborosql.dialect; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -24,7 +23,7 @@ public class H2Dialect extends AbstractDialect { * Timeout trying to lock table {0}; SQL statement: [50200-199] * */ - private static final Set pessimisticLockingErrorCodes = Collections.singleton("50200"); + private static final Set pessimisticLockingErrorCodes = Set.of("50200"); /** * コンストラクタ diff --git a/src/main/java/jp/co/future/uroborosql/dialect/MsSqlDialect.java b/src/main/java/jp/co/future/uroborosql/dialect/MsSqlDialect.java index 99ca68d2..9669e54b 100644 --- a/src/main/java/jp/co/future/uroborosql/dialect/MsSqlDialect.java +++ b/src/main/java/jp/co/future/uroborosql/dialect/MsSqlDialect.java @@ -7,7 +7,6 @@ package jp.co.future.uroborosql.dialect; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -24,7 +23,7 @@ public class MsSqlDialect extends AbstractDialect { * 悲観ロックのErrorCode もしくは SqlState. MSSQLの場合はErrorCodeで判定する. *
SQL Error [1222] [S00045]: ロック要求がタイムアウトしました。 
*/ - private static final Set pessimisticLockingErrorCodes = Collections.singleton("1222"); + private static final Set pessimisticLockingErrorCodes = Set.of("1222"); /** * コンストラクタ diff --git a/src/main/java/jp/co/future/uroborosql/dialect/MySqlDialect.java b/src/main/java/jp/co/future/uroborosql/dialect/MySqlDialect.java index 1e963172..45e566de 100644 --- a/src/main/java/jp/co/future/uroborosql/dialect/MySqlDialect.java +++ b/src/main/java/jp/co/future/uroborosql/dialect/MySqlDialect.java @@ -6,7 +6,6 @@ */ package jp.co.future.uroborosql.dialect; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -23,7 +22,7 @@ public class MySqlDialect extends AbstractDialect { * 悲観ロックのErrorCode もしくは SqlState. MySQLの場合はErrorCodeで判定する. *
ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
*/ - private static final Set pessimisticLockingErrorCodes = Collections.singleton("3572"); + private static final Set pessimisticLockingErrorCodes = Set.of("3572"); /** * コンストラクタ diff --git a/src/main/java/jp/co/future/uroborosql/dialect/PostgresqlDialect.java b/src/main/java/jp/co/future/uroborosql/dialect/PostgresqlDialect.java index edf759ec..5fa5bb94 100644 --- a/src/main/java/jp/co/future/uroborosql/dialect/PostgresqlDialect.java +++ b/src/main/java/jp/co/future/uroborosql/dialect/PostgresqlDialect.java @@ -8,7 +8,6 @@ import java.sql.JDBCType; import java.sql.SQLType; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -25,7 +24,7 @@ public class PostgresqlDialect extends AbstractDialect { * 悲観ロックのErrorCode もしくは SqlState. Postgresqlの場合はSqlStateで判定する. *
Error [55P03]: ERROR: リレーション"XXX"の行ロックを取得できませんでした
*/ - private static final Set pessimisticLockingErrorCodes = Collections.singleton("55P03"); + private static final Set pessimisticLockingErrorCodes = Set.of("55P03"); /** * コンストラクタ diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java index 6a848b5d..277c845a 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/AbstractSecretColumnEventSubscriber.java @@ -45,8 +45,11 @@ * */ public abstract class AbstractSecretColumnEventSubscriber extends EventSubscriber { - /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log.event"); + /** イベントロガー */ + private static final Logger EVENT_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.event"); + + /** 設定ロガー */ + private static final Logger SETTING_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.setting"); /** 暗号キー */ private SecretKey secretKey = null; @@ -111,28 +114,28 @@ public void initialize() { KeyStore store; try { if (StringUtils.isBlank(getKeyStoreFilePath())) { - LOG.error("Invalid KeyStore file path. Path:{}", getKeyStoreFilePath()); + SETTING_LOG.error("Invalid KeyStore file path. Path:{}", getKeyStoreFilePath()); setSkip(true); return; } var storeFile = toPath(getKeyStoreFilePath()); if (!Files.exists(storeFile)) { - LOG.error("Not found KeyStore file path. Path:{}", getKeyStoreFilePath()); + SETTING_LOG.error("Not found KeyStore file path. Path:{}", getKeyStoreFilePath()); setSkip(true); return; } if (Files.isDirectory(storeFile)) { - LOG.error("Invalid KeyStore file path. Path:{}", getKeyStoreFilePath()); + SETTING_LOG.error("Invalid KeyStore file path. Path:{}", getKeyStoreFilePath()); setSkip(true); return; } if (StringUtils.isBlank(getStorePassword())) { - LOG.error("Invalid password for access KeyStore."); + SETTING_LOG.error("Invalid password for access KeyStore."); setSkip(true); return; } if (StringUtils.isBlank(getAlias())) { - LOG.error("No alias for access KeyStore."); + SETTING_LOG.error("No alias for access KeyStore."); setSkip(true); return; } @@ -154,7 +157,7 @@ public void initialize() { encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey); useIV = encryptCipher.getIV() != null; } catch (Exception ex) { - LOG.error("Failed to acquire secret key.", ex); + SETTING_LOG.error("Failed to acquire secret key.", ex); setSkip(true); } @@ -190,7 +193,9 @@ void beforeSetParameter(final BeforeSetParameterEvent evt) { new Parameter(key, encrypt(encryptCipher, secretKey, objStr))); } } catch (Exception ex) { - LOG.warn("Encrypt Exception key:{}", key); + if (EVENT_LOG.isWarnEnabled()) { + EVENT_LOG.warn("Encrypt Exception key:{}", key); + } } } } @@ -208,7 +213,7 @@ void sqlQuery(final SqlQueryEvent evt) { evt.setResultSet(new SecretResultSet(evt.getResultSet(), this.createDecryptor(), getCryptColumnNames(), getCharset())); } catch (Exception ex) { - LOG.error("Failed to create SecretResultSet.", ex); + EVENT_LOG.error("Failed to create SecretResultSet.", ex); } } @@ -365,7 +370,8 @@ public T setCharset(final String charset) { this.charset = Charset.forName(charset); } catch (UnsupportedCharsetException ex) { this.charset = StandardCharsets.UTF_8; - LOG.error("The specified character set could not be converted to {}. Set the default character set({}).", + SETTING_LOG.error( + "The specified character set could not be converted to {}. Set the default character set({}).", charset, this.charset); } return (T) this; diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java index 0fcce052..82181fce 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/AuditLogEventSubscriber.java @@ -24,8 +24,8 @@ * */ public class AuditLogEventSubscriber extends EventSubscriber { - /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log.event"); + /** イベントロガー */ + private static final Logger EVENT_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.event"); /** 機能名取得用のパラメータキー名 */ private String funcIdKey = "_funcId"; @@ -87,8 +87,8 @@ void sqlQuery(final SqlQueryEvent evt) { funcId = DEFAULT_FUNC_ID; } - if (LOG.isDebugEnabled()) { - LOG.debug("{}", new AuditData(userName, + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("AuditData: {}", new AuditData(userName, funcId, evt.getExecutionContext().getSqlId(), evt.getExecutionContext().getSqlName(), @@ -110,8 +110,8 @@ void sqlUpdate(final SqlUpdateEvent evt) { funcId = DEFAULT_FUNC_ID; } - if (LOG.isDebugEnabled()) { - LOG.debug("{}", new AuditData(userName, + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("AuditData: {}", new AuditData(userName, funcId, evt.getExecutionContext().getSqlId(), evt.getExecutionContext().getSqlName(), @@ -133,13 +133,13 @@ void sqlBatch(final SqlBatchEvent evt) { funcId = DEFAULT_FUNC_ID; } var rowCount = -1; - if (LOG.isDebugEnabled()) { + if (EVENT_LOG.isDebugEnabled()) { try { rowCount = evt.getPreparedStatement().getUpdateCount(); } catch (SQLException ex) { // ここでの例外は実処理に影響を及ぼさないよう握りつぶす } - LOG.debug("{}", new AuditData(userName, + EVENT_LOG.debug("AuditData: {}", new AuditData(userName, funcId, evt.getExecutionContext().getSqlId(), evt.getExecutionContext().getSqlName(), diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java index b5a60260..1e041041 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/DebugEventSubscriber.java @@ -26,7 +26,7 @@ */ public class DebugEventSubscriber extends EventSubscriber { /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log.event"); + private static final Logger EVENT_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.event"); @Override public void initialize() { @@ -40,56 +40,57 @@ public void initialize() { } void afterBeginTransaction(final AfterBeginTransactionEvent evt) { - if (LOG.isDebugEnabled()) { + if (EVENT_LOG.isDebugEnabled()) { try { - LOG.debug("Begin Transaction - connection:{}", + EVENT_LOG.debug("Begin Transaction - connection:{}", evt.getTransactionContext().getConnection(), evt.occurredOn()); } catch (SQLException e) { - LOG.error(e.getMessage(), e); + EVENT_LOG.error(e.getMessage(), e); } } } void beforeEndTransaction(final BeforeEndTransactionEvent evt) { - if (LOG.isDebugEnabled()) { + if (EVENT_LOG.isDebugEnabled()) { try { - LOG.debug("End Transaction - connection:{}, result:{}", evt.getTransactionContext().getConnection(), + EVENT_LOG.debug("End Transaction - connection:{}, result:{}", + evt.getTransactionContext().getConnection(), evt.getResult()); } catch (SQLException e) { - LOG.error(e.getMessage(), e); + EVENT_LOG.error(e.getMessage(), e); } } } void beforeSetParameter(final BeforeSetParameterEvent evt) { - if (LOG.isDebugEnabled()) { - LOG.debug("Before Set Parameter - Parameter:{}", evt.getParameter()); + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("Before Set Parameter - Parameter:{}", evt.getParameter()); } } void afterGetOutParameter(final AfterGetOutParameterEvent evt) { - if (LOG.isDebugEnabled()) { - LOG.debug("After Get OutParameter - key:{}, value:{}. parameterIndex:{}", + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("After Get OutParameter - key:{}, value:{}. parameterIndex:{}", evt.getKey(), evt.getValue(), evt.getParameterIndex()); } } void sqlQuery(final SqlQueryEvent evt) { - if (LOG.isDebugEnabled()) { - LOG.debug("Execute Query - sqlName:{} executed.", evt.getExecutionContext().getSqlName()); - LOG.trace("Execute Query sql:{}", evt.getPreparedStatement()); + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("Execute Query - sqlName:{} executed.", evt.getExecutionContext().getSqlName()); + EVENT_LOG.trace("Execute Query sql:{}", evt.getPreparedStatement()); } } void sqlUpdate(final SqlUpdateEvent evt) { - if (LOG.isDebugEnabled()) { - LOG.debug("Execute Update - sqlName:{} executed. Count:{} items.", + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("Execute Update - sqlName:{} executed. Count:{} items.", evt.getExecutionContext().getSqlName(), evt.getCount()); } } void sqlBatch(final SqlBatchEvent evt) { - if (LOG.isDebugEnabled()) { + if (EVENT_LOG.isDebugEnabled()) { var counts = evt.getCounts(); try { counts = new int[] { evt.getPreparedStatement().getUpdateCount() }; @@ -101,7 +102,7 @@ void sqlBatch(final SqlBatchEvent evt) { for (int val : counts) { builder.append(val).append(", "); } - LOG.debug("Execute Update - sqlName:{} executed. Results:{}", + EVENT_LOG.debug("Execute Update - sqlName:{} executed. Results:{}", evt.getExecutionContext().getSqlName(), counts); } } diff --git a/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java b/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java index 28e96376..904bcc1d 100644 --- a/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java +++ b/src/main/java/jp/co/future/uroborosql/event/subscriber/DumpResultEventSubscriber.java @@ -37,7 +37,7 @@ */ public class DumpResultEventSubscriber extends EventSubscriber { /** ロガー */ - private static final Logger LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.log.event"); + private static final Logger EVENT_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.event"); /** 文字数計算用のエンコーディング */ private static final String ENCODING_SHIFT_JIS = "Shift-JIS"; @@ -56,12 +56,13 @@ public void initialize() { void sqlQuery(final SqlQueryEvent evt) { try { if (evt.getResultSet().getType() == ResultSet.TYPE_FORWARD_ONLY) { - LOG.warn( - "ResultSet type is TYPE_FORWARD_ONLY. DumpResultEventSubscriber use ResultSet#beforeFirst(). Please Set TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE."); + if (EVENT_LOG.isWarnEnabled()) { + EVENT_LOG.warn( + "ResultSet type is TYPE_FORWARD_ONLY. DumpResultEventSubscriber use ResultSet#beforeFirst(). Please Set TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE."); + } } - if (LOG.isInfoEnabled()) { - var builder = displayResult(evt.getResultSet()); - LOG.debug("{}", builder); + if (EVENT_LOG.isDebugEnabled()) { + EVENT_LOG.debug("{}", displayResult(evt.getResultSet())); } } catch (SQLException e) { e.printStackTrace(); diff --git a/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java b/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java index 5cf95c6d..376c5be9 100644 --- a/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java +++ b/src/main/java/jp/co/future/uroborosql/expr/spel/SpelExpressionParser.java @@ -29,10 +29,10 @@ */ public class SpelExpressionParser extends AbstractExpressionParser { /** 評価式のパーサー */ - private static org.springframework.expression.ExpressionParser parser; + private static final org.springframework.expression.ExpressionParser parser = new org.springframework.expression.spel.standard.SpelExpressionParser(); /** TransformContextに対するプロパティアクセサ */ - private static TransformContextPropertyAccessor transformContextPropertyAccessor; + private TransformContextPropertyAccessor transformContextPropertyAccessor; /** * コンストラクタ @@ -48,7 +48,6 @@ public SpelExpressionParser() { @Override public void initialize() { super.initialize(); - parser = new org.springframework.expression.spel.standard.SpelExpressionParser(); transformContextPropertyAccessor = new TransformContextPropertyAccessor( getSqlConfig().getDialect().getSqlFunction()); } @@ -68,7 +67,7 @@ public Expression parse(final String expression) { * * @author H.Sugimoto */ - private static class SpringElExpression implements Expression { + private class SpringElExpression implements Expression { /** 評価式 */ private final org.springframework.expression.Expression expr; diff --git a/src/main/java/jp/co/future/uroborosql/mapping/JavaType.java b/src/main/java/jp/co/future/uroborosql/mapping/JavaType.java index f257c034..2d46961d 100644 --- a/src/main/java/jp/co/future/uroborosql/mapping/JavaType.java +++ b/src/main/java/jp/co/future/uroborosql/mapping/JavaType.java @@ -67,22 +67,22 @@ public Class getSubclass(final Class type) { /** * スーパークラス・またはインタフェースを表すTypeを返す。 * - * @param parentclass スーパークラス・またはインタフェース + * @param parentClass スーパークラス・またはインタフェース * @return Type */ - public Type getGenericParentClass(final Class parentclass) { - return this.generics.computeIfAbsent(parentclass, this::findGenericParentClass); + public Type getGenericParentClass(final Class parentClass) { + return this.generics.computeIfAbsent(parentClass, this::findGenericParentClass); } - private Type findGenericParentClass(final Class parentclass) { - Class subclass = getSubclass(parentclass); + private Type findGenericParentClass(final Class parentClass) { + Class subclass = getSubclass(parentClass); Class superclass = subclass.getSuperclass(); - if (superclass != null && superclass.equals(parentclass)) { + if (superclass != null && superclass.equals(parentClass)) { return subclass.getGenericSuperclass(); } var interfaces = subclass.getInterfaces(); for (var i = 0; i < interfaces.length; i++) { - if (interfaces[i].equals(parentclass)) { + if (interfaces[i].equals(parentClass)) { return subclass.getGenericInterfaces()[i]; } } diff --git a/src/main/java/jp/co/future/uroborosql/mapping/MappingColumn.java b/src/main/java/jp/co/future/uroborosql/mapping/MappingColumn.java index f0d43987..e4a87888 100644 --- a/src/main/java/jp/co/future/uroborosql/mapping/MappingColumn.java +++ b/src/main/java/jp/co/future/uroborosql/mapping/MappingColumn.java @@ -6,6 +6,9 @@ */ package jp.co.future.uroborosql.mapping; +import java.time.temporal.Temporal; +import java.util.Optional; + import jp.co.future.uroborosql.enums.SqlKind; import jp.co.future.uroborosql.mapping.annotations.GeneratedValue; import jp.co.future.uroborosql.mapping.annotations.SequenceGenerator; @@ -20,7 +23,7 @@ public interface MappingColumn { /** - * エンティティから値を取得 + * エンティティから値を取得. * * @param entity エンティティ * @return 取得した値 @@ -28,7 +31,7 @@ public interface MappingColumn { Object getValue(Object entity); /** - * エンティティに値をセット + * エンティティに値をセット. * * @param entity エンティティ * @param value 値 @@ -36,49 +39,49 @@ public interface MappingColumn { void setValue(Object entity, Object value); /** - * カラム名取得 + * カラム名取得. * * @return カラム名 */ String getName(); /** - * キャメルケースカラム名取得 + * キャメルケースカラム名取得. * * @return キャメルケースカラム名 */ String getCamelName(); /** - * {@link JavaType}取得 + * {@link JavaType}取得. * * @return {@link JavaType} */ JavaType getJavaType(); /** - * IDアノテーションが付与されているかどうか + * IDアノテーションが付与されているかどうか. * * @return IDアノテーションが付与されている場合true */ boolean isId(); /** - * {@link GeneratedValue}の取得 + * {@link GeneratedValue}の取得. * * @return {@link GeneratedValue} */ GeneratedValue getGeneratedValue(); /** - * {@link SequenceGenerator}の取得 + * {@link SequenceGenerator}の取得. * * @return {@link SequenceGenerator} */ SequenceGenerator getSequenceGenerator(); /** - * 修飾済みのシーケンス名の取得 + * 修飾済みのシーケンス名の取得. * * @return {@link SequenceGenerator} をもとに修飾したシーケンス名 */ @@ -99,14 +102,14 @@ default String getQualifiedSequenceName() { } /** - * {@link Transient}の取得 + * {@link Transient}の取得. * * @return {@link Transient} */ Transient getTransient(); /** - * 指定したSQL種別でtransientかどうかを判断する + * 指定したSQL種別でtransientかどうか. * * @param sqlKind SQL種別 * @return 指定したSQL種別でtransientの場合true @@ -114,14 +117,69 @@ default String getQualifiedSequenceName() { boolean isTransient(SqlKind sqlKind); /** - * バージョン情報カラムかどうか + * バージョン情報カラムかどうか. * * @return バージョンカラムの場合はtrue */ boolean isVersion(); /** - * {@link Version} の取得 + * Optional型のカラムかどうか. + * + * @return Optional型のカラムの場合はtrue + */ + default boolean isOptional() { + return Optional.class.equals(getJavaType().getRawType()); + } + + /** + * 文字、または文字列型のカラムかどうか. + * + * @return 文字、または文字列型のカラムの場合はtrue + */ + default boolean isString() { + var rawType = isOptional() ? getJavaType().getParam(0).getRawType() : getJavaType().getRawType(); + return String.class.equals(rawType) || + char.class.equals(rawType) || + Character.class.equals(rawType); + } + + /** + * 数値型のカラムかどうか. + * + * @return 数値型のカラムの場合はtrue + */ + default boolean isNumber() { + var rawType = isOptional() ? getJavaType().getParam(0).getRawType() : getJavaType().getRawType(); + return short.class.equals(rawType) || + int.class.equals(rawType) || + long.class.equals(rawType) || + float.class.equals(rawType) || + double.class.equals(rawType) || + Number.class.isAssignableFrom(rawType); + } + + /** + * 配列型のカラムかどうか. + * + * @return 配列型のカラムの場合はtrue + */ + default boolean isArray() { + return getJavaType().getRawType().isArray(); + } + + /** + * 時間的オブジェクト型のカラムかどうか. + * + * @return 時間的オブジェクト型のカラムの場合はtrue + */ + default boolean isTemporal() { + var rawType = isOptional() ? getJavaType().getParam(0).getRawType() : getJavaType().getRawType(); + return Temporal.class.isAssignableFrom(rawType); + } + + /** + * {@link Version} の取得. * * @return {@link Version} */ diff --git a/src/main/java/jp/co/future/uroborosql/node/IfNode.java b/src/main/java/jp/co/future/uroborosql/node/IfNode.java index 10d790fc..3c17c592 100644 --- a/src/main/java/jp/co/future/uroborosql/node/IfNode.java +++ b/src/main/java/jp/co/future/uroborosql/node/IfNode.java @@ -21,7 +21,7 @@ */ public class IfNode extends BranchNode { /** パーサーロガー */ - private static final Logger PARSER_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.parser"); + private static final Logger PARSER_LOG = LoggerFactory.getLogger("jp.co.future.uroborosql.sql.parser"); private final ExpressionParser expressionParser; /** 評価式 */ diff --git a/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java b/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java index 8454fa19..4bc5a4dc 100644 --- a/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java +++ b/src/main/java/jp/co/future/uroborosql/parameter/Parameter.java @@ -101,8 +101,10 @@ public Parameter createSubParameter(final String propertyName) { if (value instanceof Map) { subValue = ((Map) value).get(propertyName); if (subValue == null) { - LOG.warn("Set subparameter value to NULL because property can not be accessed.[{}]", - subParameterName); + if (LOG.isWarnEnabled()) { + LOG.warn("Set subparameter value to NULL because property can not be accessed.[{}]", + subParameterName); + } } } else { try { @@ -118,12 +120,16 @@ public Parameter createSubParameter(final String propertyName) { .getMethod(prefix + StringUtils.capitalize(propertyName)); subValue = method.invoke(value); } catch (Exception e2) { - LOG.warn("Set subparameter value to NULL because property can not be accessed.[{}]", - subParameterName, e2); + if (LOG.isWarnEnabled()) { + LOG.warn("Set subparameter value to NULL because property can not be accessed.[{}]", + subParameterName, e2); + } } } catch (Exception e) { - LOG.warn("Set subparameter value to NULL because property can not be accessed.[{}]", - subParameterName, e); + if (LOG.isWarnEnabled()) { + LOG.warn("Set subparameter value to NULL because property can not be accessed.[{}]", + subParameterName, e); + } } } } @@ -180,8 +186,8 @@ protected int setInParameter(final PreparedStatement preparedStatement, final in * @param index パラメータインデックス */ protected void parameterLog(final int index) { - if (SQL_LOG.isTraceEnabled() && Boolean.FALSE.toString().equals(MDC.get("SuppressParameterLogOutput"))) { - SQL_LOG.trace("Set the parameter.[INDEX[{}], {}]", index, this); + if (SQL_LOG.isInfoEnabled() && Boolean.FALSE.toString().equals(MDC.get("SuppressParameterLogOutput"))) { + SQL_LOG.info("Set the parameter.[INDEX[{}], {}]", index, this); } } diff --git a/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java b/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java index a6c78ba1..b4449063 100644 --- a/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java +++ b/src/main/java/jp/co/future/uroborosql/store/SqlResourceManagerImpl.java @@ -277,7 +277,9 @@ private void watchPath() { try { key = watcher.take(); } catch (InterruptedException ex) { - LOG.debug("WatchService catched InterruptedException."); + if (LOG.isDebugEnabled()) { + LOG.debug("WatchService caught InterruptedException."); + } break; } catch (Throwable ex) { LOG.error("Unexpected exception occurred.", ex); @@ -297,7 +299,9 @@ private void watchPath() { var dir = watchDirs.get(key); var path = dir.resolve(evt.context()); - LOG.debug("file changed.({}). path={}", kind.name(), path); + if (LOG.isDebugEnabled()) { + LOG.debug("file changed.({}). path={}", kind.name(), path); + } var isSqlFile = path.toString().endsWith(fileExtension); if (Files.isDirectory(path) || !isSqlFile) { // ENTRY_DELETEの時はFiles.isDirectory()がfalseになるので拡張子での判定も行う @@ -408,7 +412,9 @@ private void generateSqlInfos() { } else if (SCHEME_JAR.equalsIgnoreCase(scheme)) { traverseJar(url, loadPathSlash); } else { - LOG.warn("Unsupported scheme. scheme : {}, url : {}", scheme, url); + if (LOG.isWarnEnabled()) { + LOG.warn("Unsupported scheme. scheme : {}, url : {}", scheme, url); + } } } } @@ -526,7 +532,9 @@ private boolean validPath(final Path path) { * @param remove 削除指定。trueの場合、指定のPathを除外する。falseの場合は格納する */ private void traverseFile(final Path path, final boolean watch, final boolean remove) { - LOG.trace("traverseFile start. path : {}, watch : {}, remove : {}.", path, watch, remove); + if (LOG.isTraceEnabled()) { + LOG.trace("traverseFile start. path : {}, watch : {}, remove : {}.", path, watch, remove); + } if (Files.notExists(path)) { return; } @@ -559,8 +567,9 @@ private void traverseFile(final Path path, final boolean watch, final boolean re */ @SuppressWarnings("resource") private void traverseJar(final URL url, final String loadPath) { - LOG.trace("traverseJar start. url : {}, loadPath : {}.", url, loadPath); - + if (LOG.isTraceEnabled()) { + LOG.trace("traverseJar start. url : {}, loadPath : {}.", url, loadPath); + } FileSystem fs = null; try { var uri = url.toURI(); @@ -629,8 +638,10 @@ public static class SqlInfo { final List loadPaths, final Dialect dialect, final Charset charset) { - LOG.trace("SqlInfo - sqlName : {}, path : {}, dialect : {}, charset : {}.", - sqlName, path, dialect, charset); + if (LOG.isTraceEnabled()) { + LOG.trace("SqlInfo - sqlName : {}, path : {}, dialect : {}, charset : {}.", + sqlName, path, dialect, charset); + } this.sqlName = sqlName; this.dialect = dialect; this.charset = charset; @@ -650,7 +661,9 @@ private static FileTime getLastModifiedTime(final Path path) { try { return Files.getLastModifiedTime(path); } catch (IOException e) { - LOG.warn("Can't get lastModifiedTime. path:{}", path, e); + if (LOG.isWarnEnabled()) { + LOG.warn("Can't get lastModifiedTime. path:{}", path, e); + } } } return FileTime.fromMillis(0L); @@ -709,7 +722,9 @@ private String getSqlBody() { try { var body = new String(Files.readAllBytes(path), charset); sqlBody = formatSqlBody(body); - LOG.debug("Loaded SQL template.[{}]", path); + if (LOG.isDebugEnabled()) { + LOG.debug("Loaded SQL template.[{}]", path); + } } catch (IOException e) { throw new UroborosqlRuntimeException("Failed to load SQL template[" + path.toAbsolutePath().toString() + "].", e); @@ -730,7 +745,9 @@ private String getSqlBody() { var body = reader.lines() .collect(Collectors.joining(System.lineSeparator())); sqlBody = formatSqlBody(body); - LOG.debug("Loaded SQL template.[{}]", path); + if (LOG.isDebugEnabled()) { + LOG.debug("Loaded SQL template.[{}]", path); + } } } catch (IOException e) { throw new UroborosqlRuntimeException("Failed to load SQL template[" @@ -861,13 +878,17 @@ private SqlInfo computePath(final Path newPath, final boolean remove) { var currentTimeStamp = getLastModifiedTime(currentPath); if (!oldPath.equals(currentPath)) { replaceFlag = true; - LOG.debug("sql file switched. sqlName={}, oldPath={}, newPath={}, lastModified={}", sqlName, - oldPath, currentPath, currentTimeStamp.toString()); + if (LOG.isDebugEnabled()) { + LOG.debug("sql file switched. sqlName={}, oldPath={}, newPath={}, lastModified={}", sqlName, + oldPath, currentPath, currentTimeStamp.toString()); + } } else { if (!this.lastModified.equals(currentTimeStamp)) { replaceFlag = true; - LOG.debug("sql file changed. sqlName={}, path={}, lastModified={}", sqlName, currentPath, - currentTimeStamp.toString()); + if (LOG.isDebugEnabled()) { + LOG.debug("sql file changed. sqlName={}, path={}, lastModified={}", sqlName, currentPath, + currentTimeStamp.toString()); + } } } diff --git a/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java b/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java index c761fde0..8a60acea 100644 --- a/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java +++ b/src/main/java/jp/co/future/uroborosql/tx/LocalTransactionContext.java @@ -362,7 +362,9 @@ public void close() { if (connection != null && !connection.isClosed()) { connection.close(); } else { - LOG.debug("Connection close was skipped because the connection was already closed."); + if (LOG.isWarnEnabled()) { + LOG.warn("Connection close was skipped because the connection was already closed."); + } } } catch (SQLException e) { throw new UroborosqlSQLException(e); diff --git a/src/test/java/jp/co/future/uroborosql/context/ExecutionContextImplTest.java b/src/test/java/jp/co/future/uroborosql/context/ExecutionContextImplTest.java index 3b0c28e8..63d584a3 100644 --- a/src/test/java/jp/co/future/uroborosql/context/ExecutionContextImplTest.java +++ b/src/test/java/jp/co/future/uroborosql/context/ExecutionContextImplTest.java @@ -13,12 +13,19 @@ import java.io.Reader; import java.io.StringReader; import java.sql.JDBCType; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import jp.co.future.uroborosql.UroboroSQL; import jp.co.future.uroborosql.config.SqlConfig; @@ -28,6 +35,9 @@ import jp.co.future.uroborosql.parser.SqlParserImpl; public class ExecutionContextImplTest { + /** ロガー */ + protected static final Logger log = LoggerFactory.getLogger(ExecutionContextImplTest.class); + private static SqlConfig config = null; @BeforeAll @@ -43,7 +53,7 @@ private ExecutionContext getExecutionContext(final String sql) { } private String replaceLineSep(final String sql) { - return sql.replaceAll("\\[LF\\]", System.lineSeparator()); + return sql.replace("[LF]", System.lineSeparator()); } @Test @@ -90,6 +100,17 @@ void removeFirstAndKeyWordWhenWhereClause() throws Exception { "select * from test[LF]where /* comment */ --comment [LF] order = 1"); assertEquals(replaceLineSep("select * from test[LF]where /* comment */ --comment [LF] order = 1"), ctx62.getExecutableSql()); + + var startTime = Instant.now(Clock.systemDefaultZone()); + var sql = replaceLineSep("select * from test[LF]where -- /* comment */ [LF] and aaa = 1"); + for (var i = 0; i < 1000000; i++) { + var timeCtx = config.context().setSql(sql); + timeCtx.addSqlPart(sql); + timeCtx.getExecutableSql(); + } + log.info("removeFirstAndKeyWordWhenWhereClause elapsed time. {}", + DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS").format( + LocalTime.MIDNIGHT.plus(Duration.between(startTime, Instant.now(Clock.systemDefaultZone()))))); } @Test @@ -128,6 +149,18 @@ void removeFirstCommaWhenSelectClause() throws Exception { assertEquals(replaceLineSep( "with dummy as ( select * from dummy )[LF]select /* コメント:japanese comment */ [LF] aaa[LF], bbb[LF], ccc from test"), ctx8.getExecutableSql()); + + var startTime = Instant.now(Clock.systemDefaultZone()); + var sql = replaceLineSep( + "with dummy as ( select * from dummy )[LF]select /* コメント:japanese comment */ [LF], aaa[LF], bbb[LF], ccc from test"); + for (var i = 0; i < 1000000; i++) { + var timeCtx = config.context().setSql(sql); + timeCtx.addSqlPart(sql); + timeCtx.getExecutableSql(); + } + log.info("removeFirstCommaWhenSelectClause elapsed time. {}", + DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS").format( + LocalTime.MIDNIGHT.plus(Duration.between(startTime, Instant.now(Clock.systemDefaultZone()))))); } @Test @@ -168,6 +201,17 @@ void removeFirstCommaWhenOrderByClause() throws Exception { "select * from test[LF]order by --/* comment */[LF], aaa, bbb"); assertEquals(replaceLineSep("select * from test[LF]order by --/* comment */[LF] aaa, bbb"), ctx62.getExecutableSql()); + + var startTime = Instant.now(Clock.systemDefaultZone()); + var sql = replaceLineSep("select * from test[LF]order by --/* comment */[LF], aaa, bbb"); + for (var i = 0; i < 1000000; i++) { + var timeCtx = config.context().setSql(sql); + timeCtx.addSqlPart(sql); + timeCtx.getExecutableSql(); + } + log.info("removeFirstCommaWhenOrderByClause elapsed time. {}", + DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS").format( + LocalTime.MIDNIGHT.plus(Duration.between(startTime, Instant.now(Clock.systemDefaultZone()))))); } @Test @@ -210,6 +254,17 @@ void removeFirstCommaWhenGroupByClause() throws Exception { "select * from test[LF]group by /* comment */ --aaa[LF], aaa, bbb"); assertEquals(replaceLineSep("select * from test[LF]group by /* comment */ --aaa[LF] aaa, bbb"), ctx62.getExecutableSql()); + + var startTime = Instant.now(Clock.systemDefaultZone()); + var sql = replaceLineSep("select * from test[LF]group by /* comment */ --aaa[LF], aaa, bbb"); + for (var i = 0; i < 1000000; i++) { + var timeCtx = config.context().setSql(sql); + timeCtx.addSqlPart(sql); + timeCtx.getExecutableSql(); + } + log.info("removeFirstCommaWhenGroupByClause elapsed time. {}", + DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS").format( + LocalTime.MIDNIGHT.plus(Duration.between(startTime, Instant.now(Clock.systemDefaultZone()))))); } @Test @@ -261,6 +316,18 @@ void removeFirstCommaWhenStartBracket() throws Exception { replaceLineSep( "insert into[LF](--comment[LF] aaa[LF], bbb[LF], ccc[LF]) values (/*comment*/[LF]111,[LF]222,[LF]333[LF])"), ctx52.getExecutableSql()); + + var startTime = Instant.now(Clock.systemDefaultZone()); + var sql = replaceLineSep( + "insert into[LF](--comment[LF], aaa[LF], bbb[LF], ccc[LF]) values (,/*comment*/[LF]111,[LF]222,[LF]333[LF])"); + for (var i = 0; i < 1000000; i++) { + var timeCtx = config.context().setSql(sql); + timeCtx.addSqlPart(sql); + timeCtx.getExecutableSql(); + } + log.info("removeFirstCommaWhenStartBracket elapsed time. {}", + DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS").format( + LocalTime.MIDNIGHT.plus(Duration.between(startTime, Instant.now(Clock.systemDefaultZone()))))); } @Test @@ -317,6 +384,17 @@ void removeFirstCommaWhenSetClause() throws Exception { "select[LF], aaa,[LF]code_set,[LF]bbb,[LF]ccc[LF]from[LF]test[LF]where[LF]1 = 1"); assertEquals(replaceLineSep("select[LF] aaa,[LF]code_set,[LF]bbb,[LF]ccc[LF]from[LF]test[LF]where[LF]1 = 1"), ctx63.getExecutableSql()); + + var startTime = Instant.now(Clock.systemDefaultZone()); + var sql = replaceLineSep("select[LF], aaa,[LF]code_set,[LF]bbb,[LF]ccc[LF]from[LF]test[LF]where[LF]1 = 1"); + for (var i = 0; i < 1000000; i++) { + var timeCtx = config.context().setSql(sql); + timeCtx.addSqlPart(sql); + timeCtx.getExecutableSql(); + } + log.info("removeFirstCommaWhenSetClause elapsed time. {}", + DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS").format( + LocalTime.MIDNIGHT.plus(Duration.between(startTime, Instant.now(Clock.systemDefaultZone()))))); } @Test diff --git a/src/test/java/jp/co/future/uroborosql/mapping/DefaultEntityHandlerTest.java b/src/test/java/jp/co/future/uroborosql/mapping/DefaultEntityHandlerTest.java index 9262ab53..283d4a3d 100644 --- a/src/test/java/jp/co/future/uroborosql/mapping/DefaultEntityHandlerTest.java +++ b/src/test/java/jp/co/future/uroborosql/mapping/DefaultEntityHandlerTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; +import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; @@ -331,6 +332,112 @@ void testQuery4() throws Exception { } } + @Test + public void testQuery5() throws Exception { + + try (var agent = config.agent()) { + agent.required(() -> { + var test1 = new TestEntity4(1L, "name1", new BigDecimal("20"), + LocalDate.of(1990, Month.APRIL, 1)); + agent.insert(test1); + var test2 = new TestEntity4(2L, "name2", new BigDecimal("21"), + LocalDate.of(1990, Month.MAY, 1)); + agent.insert(test2); + var test3 = new TestEntity4(3L, "name3", new BigDecimal("22"), + LocalDate.of(1990, Month.MAY, 1)); + agent.insert(test3); + var test4 = new TestEntity4(4L, "name4", new BigDecimal("23"), null); + agent.insert(test4); + + var count1 = agent.query(TestEntity4.class).count(); + assertThat(count1, is(4L)); + var count2 = agent.query(TestEntity4.class).count(TestEntity4.Names.Birthday); + assertThat(count2, is(3L)); + + var sum = agent.query(TestEntity4.class).sum(TestEntity4.Names.Age); + assertThat(sum, is(new BigDecimal("86"))); + + var min = agent.query(TestEntity4.class).min(TestEntity4.Names.Age); + assertThat(min, is(new BigDecimal("20"))); + + var minName = agent.query(TestEntity4.class).min(TestEntity4.Names.Name); + assertThat(minName, is("name1")); + + long max = agent.query(TestEntity4.class).max(TestEntity4.Names.Id); + assertThat(max, is(4L)); + + var maxDate = agent.query(TestEntity4.class).max(TestEntity4.Names.Birthday); + assertThat(maxDate, is(LocalDate.of(1990, Month.MAY, 1))); + }); + } + } + + @Test + public void testQuery6() throws Exception { + + try (var agent = config.agent()) { + agent.required(() -> { + var test1 = new TestEntity5(1L, "name1", Optional.ofNullable(new BigDecimal("20")), + LocalDate.of(1990, Month.APRIL, 1)); + agent.insert(test1); + var test2 = new TestEntity5(2L, "name2", Optional.ofNullable(new BigDecimal("21")), + LocalDate.of(1990, Month.MAY, 1)); + agent.insert(test2); + var test3 = new TestEntity5(3L, "name3", Optional.ofNullable(new BigDecimal("22")), + LocalDate.of(1990, Month.MAY, 1)); + agent.insert(test3); + var test4 = new TestEntity5(4L, "name4", Optional.empty(), null); + agent.insert(test4); + + var count1 = agent.query(TestEntity5.class).count(); + assertThat(count1, is(4L)); + var count2 = agent.query(TestEntity5.class).count(TestEntity5.Names.Birthday); + assertThat(count2, is(3L)); + + Optional sum = agent.query(TestEntity5.class).sum(TestEntity5.Names.Age); + assertThat(sum.orElseThrow(IllegalStateException::new), is(new BigDecimal("63"))); + + Optional min = agent.query(TestEntity5.class).min(TestEntity5.Names.Age); + assertThat(min.orElseThrow(IllegalStateException::new), is(new BigDecimal("20"))); + + var minName = agent.query(TestEntity5.class).min(TestEntity5.Names.Name); + assertThat(minName, is("name1")); + + long max = agent.query(TestEntity5.class).max(TestEntity5.Names.Id); + assertThat(max, is(4L)); + + var maxDate = agent.query(TestEntity5.class).max(TestEntity5.Names.Birthday); + assertThat(maxDate, is(LocalDate.of(1990, Month.MAY, 1))); + + }); + } + } + + @Test + public void testQuery7() throws Exception { + + try (var agent = config.agent()) { + agent.required(() -> { + var test1 = new TestEntity5(1L, "name1", Optional.empty(), + LocalDate.of(1990, Month.APRIL, 1)); + agent.insert(test1); + var test2 = new TestEntity5(2L, "name2", Optional.empty(), + LocalDate.of(1990, Month.MAY, 1)); + agent.insert(test2); + + Optional sum = agent.query(TestEntity5.class).sum(TestEntity5.Names.Age); + assertThat(sum.isPresent(), is(false)); + + Optional min = agent.query(TestEntity5.class).min(TestEntity5.Names.Age); + assertThat(min.isPresent(), is(false)); + + Optional max = agent.query(TestEntity5.class).max(TestEntity5.Names.Age); + assertThat(max.isPresent(), is(false)); + + }); + } + } + @Test void testQueryCountUnmatchColumn() throws Exception { assertThrows(UroborosqlRuntimeException.class, () -> { diff --git a/src/test/java/jp/co/future/uroborosql/mapping/MappingColumnTest.java b/src/test/java/jp/co/future/uroborosql/mapping/MappingColumnTest.java new file mode 100644 index 00000000..05612ecd --- /dev/null +++ b/src/test/java/jp/co/future/uroborosql/mapping/MappingColumnTest.java @@ -0,0 +1,1361 @@ +package jp.co.future.uroborosql.mapping; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.OffsetTime; +import java.time.Year; +import java.time.YearMonth; +import java.time.ZonedDateTime; +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import jp.co.future.uroborosql.mapping.annotations.Table; + +public class MappingColumnTest { + + @Test + public void testMappingColumnType() throws Exception { + // string + var col = MappingUtils.getMappingColumn(TestColType.class, "colStr"); + assertThat(col.getJavaType().getRawType(), sameInstance(String.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(true)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colChar"); + assertThat(col.getJavaType().getRawType(), sameInstance(char.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(true)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colCharacter"); + assertThat(col.getJavaType().getRawType(), sameInstance(Character.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(true)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + // number + col = MappingUtils.getMappingColumn(TestColType.class, "colShort"); + assertThat(col.getJavaType().getRawType(), sameInstance(short.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colShortType"); + assertThat(col.getJavaType().getRawType(), sameInstance(Short.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colInt"); + assertThat(col.getJavaType().getRawType(), sameInstance(int.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colIntType"); + assertThat(col.getJavaType().getRawType(), sameInstance(Integer.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLong"); + assertThat(col.getJavaType().getRawType(), sameInstance(long.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLongType"); + assertThat(col.getJavaType().getRawType(), sameInstance(Long.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colFloat"); + assertThat(col.getJavaType().getRawType(), sameInstance(float.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colFloatType"); + assertThat(col.getJavaType().getRawType(), sameInstance(Float.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colDouble"); + assertThat(col.getJavaType().getRawType(), sameInstance(double.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colDoubleType"); + assertThat(col.getJavaType().getRawType(), sameInstance(Double.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colBigInteger"); + assertThat(col.getJavaType().getRawType(), sameInstance(BigInteger.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colBigDecimal"); + assertThat(col.getJavaType().getRawType(), sameInstance(BigDecimal.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + // temporal + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalDate"); + assertThat(col.getJavaType().getRawType(), sameInstance(LocalDate.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalDateTime"); + assertThat(col.getJavaType().getRawType(), sameInstance(LocalDateTime.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colOffsetDateTime"); + assertThat(col.getJavaType().getRawType(), sameInstance(OffsetDateTime.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colZonedDateTime"); + assertThat(col.getJavaType().getRawType(), sameInstance(ZonedDateTime.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalTime"); + assertThat(col.getJavaType().getRawType(), sameInstance(LocalTime.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colOffsetTime"); + assertThat(col.getJavaType().getRawType(), sameInstance(OffsetTime.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colYear"); + assertThat(col.getJavaType().getRawType(), sameInstance(Year.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colYearMonth"); + assertThat(col.getJavaType().getRawType(), sameInstance(YearMonth.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + // lagacy datetime + col = MappingUtils.getMappingColumn(TestColType.class, "colUtilDate"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.util.Date.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlDate"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.sql.Date.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlTime"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.sql.Time.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlTimestamp"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.sql.Timestamp.class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + } + + @Test + public void testMappingColumnTypeOptional() throws Exception { + // string + var col = MappingUtils.getMappingColumn(TestColType.class, "colStrOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(String.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(true)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colCharacterOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Character.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(true)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + // number + col = MappingUtils.getMappingColumn(TestColType.class, "colShortTypeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Short.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colIntTypeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Integer.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLongTypeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Long.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colFloatTypeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Float.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colDoubleTypeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Double.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colBigIntegerOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(BigInteger.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colBigDecimalOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(BigDecimal.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(true)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + // temporal + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalDateOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(LocalDate.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalDateTimeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(LocalDateTime.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colOffsetDateTimeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(OffsetDateTime.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colZonedDateTimeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(ZonedDateTime.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalTimeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(LocalTime.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colOffsetTimeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(OffsetTime.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colYearOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(Year.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colYearMonthOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(YearMonth.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(true)); + + // lagacy datetime + col = MappingUtils.getMappingColumn(TestColType.class, "colUtilDateOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(java.util.Date.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlDateOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(java.sql.Date.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlTimeOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(java.sql.Time.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlTimestampOpt"); + assertThat(col.getJavaType().getRawType(), sameInstance(Optional.class)); + assertThat(col.getJavaType().getParam(0).getRawType(), sameInstance(java.sql.Timestamp.class)); + assertThat(col.isOptional(), is(true)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(false)); + assertThat(col.isTemporal(), is(false)); + + } + + @Test + public void testMappingColumnTypeArray() throws Exception { + // string + var col = MappingUtils.getMappingColumn(TestColType.class, "colStrArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(String[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colCharArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(char[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colCharacterArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Character[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + // number + col = MappingUtils.getMappingColumn(TestColType.class, "colShortArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(short[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colShortTypeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Short[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colIntArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(int[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colIntTypeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Integer[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLongArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(long[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLongTypeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Long[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colFloatArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(float[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colFloatTypeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Float[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colDoubleArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(double[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colDoubleTypeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Double[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colBigIntegerArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(BigInteger[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colBigDecimalArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(BigDecimal[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + // temporal + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalDateArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(LocalDate[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalDateTimeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(LocalDateTime[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colOffsetDateTimeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(OffsetDateTime[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colZonedDateTimeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(ZonedDateTime[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colLocalTimeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(LocalTime[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colOffsetTimeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(OffsetTime[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colYearArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(Year[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colYearMonthArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(YearMonth[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + // lagacy datetime + col = MappingUtils.getMappingColumn(TestColType.class, "colUtilDateArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.util.Date[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlDateArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.sql.Date[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlTimeArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.sql.Time[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + col = MappingUtils.getMappingColumn(TestColType.class, "colSqlTimestampArr"); + assertThat(col.getJavaType().getRawType(), sameInstance(java.sql.Timestamp[].class)); + assertThat(col.isOptional(), is(false)); + assertThat(col.isString(), is(false)); + assertThat(col.isNumber(), is(false)); + assertThat(col.isArray(), is(true)); + assertThat(col.isTemporal(), is(false)); + + } + + @Test + public void testClearCache() throws Exception { + MappingUtils.clearCache(); + } + + @Table(name = "TEST") + public static class TestColType { + private String colStr; + private char colChar; + private Character colCharacter; + private short colShort; + private Short colShortType; + private int colInt; + private Integer colIntType; + private long colLong; + private Long colLongType; + private float colFloat; + private Float colFloatType; + private double colDouble; + private Double colDoubleType; + private BigInteger colBigInteger; + private BigDecimal colBigDecimal; + private LocalDate colLocalDate; + private LocalDateTime colLocalDateTime; + private OffsetDateTime colOffsetDateTime; + private ZonedDateTime colZonedDateTime; + private LocalTime colLocalTime; + private OffsetTime colOffsetTime; + private Year colYear; + private YearMonth colYearMonth; + private java.util.Date colUtilDate; + private java.sql.Date colSqlDate; + private java.sql.Time colSqlTime; + private java.sql.Timestamp colSqlTimestamp; + + // Optional + private Optional colStrOpt; + private Optional colCharacterOpt; + private Optional colShortTypeOpt; + private Optional colIntTypeOpt; + private Optional colLongTypeOpt; + private Optional colFloatTypeOpt; + private Optional colDoubleTypeOpt; + private Optional colBigIntegerOpt; + private Optional colBigDecimalOpt; + private Optional colLocalDateOpt; + private Optional colLocalDateTimeOpt; + private Optional colOffsetDateTimeOpt; + private Optional colZonedDateTimeOpt; + private Optional colLocalTimeOpt; + private Optional colOffsetTimeOpt; + private Optional colYearOpt; + private Optional colYearMonthOpt; + private Optional colUtilDateOpt; + private Optional colSqlDateOpt; + private Optional colSqlTimeOpt; + private Optional colSqlTimestampOpt; + + // Array + private String[] colStrArr; + private char[] colCharArr; + private Character[] colCharacterArr; + private short[] colShortArr; + private Short[] colShortTypeArr; + private int[] colIntArr; + private Integer[] colIntTypeArr; + private long[] colLongArr; + private Long[] colLongTypeArr; + private float[] colFloatArr; + private Float[] colFloatTypeArr; + private double[] colDoubleArr; + private Double[] colDoubleTypeArr; + private BigInteger[] colBigIntegerArr; + private BigDecimal[] colBigDecimalArr; + private LocalDate[] colLocalDateArr; + private LocalDateTime[] colLocalDateTimeArr; + private OffsetDateTime[] colOffsetDateTimeArr; + private ZonedDateTime[] colZonedDateTimeArr; + private LocalTime[] colLocalTimeArr; + private OffsetTime[] colOffsetTimeArr; + private Year[] colYearArr; + private YearMonth[] colYearMonthArr; + private java.util.Date[] colUtilDateArr; + private java.sql.Date[] colSqlDateArr; + private java.sql.Time[] colSqlTimeArr; + private java.sql.Timestamp[] colSqlTimestampArr; + + public TestColType() { + } + + public String getColStr() { + return colStr; + } + + public void setColStr(final String colStr) { + this.colStr = colStr; + } + + public char getColChar() { + return colChar; + } + + public void setColChar(final char colChar) { + this.colChar = colChar; + } + + public Character getColCharacter() { + return colCharacter; + } + + public void setColCharacter(final Character colCharacter) { + this.colCharacter = colCharacter; + } + + public short getColShort() { + return colShort; + } + + public void setColShort(final short colShort) { + this.colShort = colShort; + } + + public Short getColShortType() { + return colShortType; + } + + public void setColShortType(final Short colShortType) { + this.colShortType = colShortType; + } + + public int getColInt() { + return colInt; + } + + public void setColInt(final int colInt) { + this.colInt = colInt; + } + + public Integer getColIntType() { + return colIntType; + } + + public void setColIntType(final Integer colIntType) { + this.colIntType = colIntType; + } + + public long getColLong() { + return colLong; + } + + public void setColLong(final long colLong) { + this.colLong = colLong; + } + + public Long getColLongType() { + return colLongType; + } + + public void setColLongType(final Long colLongType) { + this.colLongType = colLongType; + } + + public float getColFloat() { + return colFloat; + } + + public void setColFloat(final float colFloat) { + this.colFloat = colFloat; + } + + public Float getColFloatType() { + return colFloatType; + } + + public void setColFloatType(final Float colFloatType) { + this.colFloatType = colFloatType; + } + + public double getColDouble() { + return colDouble; + } + + public void setColDouble(final double colDouble) { + this.colDouble = colDouble; + } + + public Double getColDoubleType() { + return colDoubleType; + } + + public void setColDoubleType(final Double colDoubleType) { + this.colDoubleType = colDoubleType; + } + + public BigInteger getColBigInteger() { + return colBigInteger; + } + + public void setColBigInteger(final BigInteger colBigInteger) { + this.colBigInteger = colBigInteger; + } + + public BigDecimal getColBigDecimal() { + return colBigDecimal; + } + + public void setColBigDecimal(final BigDecimal colBigDecimal) { + this.colBigDecimal = colBigDecimal; + } + + public LocalDate getColLocalDate() { + return colLocalDate; + } + + public void setColLocalDate(final LocalDate colLocalDate) { + this.colLocalDate = colLocalDate; + } + + public LocalDateTime getColLocalDateTime() { + return colLocalDateTime; + } + + public void setColLocalDateTime(final LocalDateTime colLocalDateTime) { + this.colLocalDateTime = colLocalDateTime; + } + + public OffsetDateTime getColOffsetDateTime() { + return colOffsetDateTime; + } + + public void setColOffsetDateTime(final OffsetDateTime colOffsetDateTime) { + this.colOffsetDateTime = colOffsetDateTime; + } + + public ZonedDateTime getColZonedDateTime() { + return colZonedDateTime; + } + + public void setColZonedDateTime(final ZonedDateTime colZonedDateTime) { + this.colZonedDateTime = colZonedDateTime; + } + + public LocalTime getColLocalTime() { + return colLocalTime; + } + + public void setColLocalTime(final LocalTime colLocalTime) { + this.colLocalTime = colLocalTime; + } + + public OffsetTime getColOffsetTime() { + return colOffsetTime; + } + + public void setColOffsetTime(final OffsetTime colOffsetTime) { + this.colOffsetTime = colOffsetTime; + } + + public Year getColYear() { + return colYear; + } + + public void setColYear(final Year colYear) { + this.colYear = colYear; + } + + public YearMonth getColYearMonth() { + return colYearMonth; + } + + public void setColYearMonth(final YearMonth colYearMonth) { + this.colYearMonth = colYearMonth; + } + + public java.util.Date getColUtilDate() { + return colUtilDate; + } + + public void setColUtilDate(final java.util.Date colUtilDate) { + this.colUtilDate = colUtilDate; + } + + public java.sql.Date getColSqlDate() { + return colSqlDate; + } + + public void setColSqlDate(final java.sql.Date colSqlDate) { + this.colSqlDate = colSqlDate; + } + + public java.sql.Time getColSqlTime() { + return colSqlTime; + } + + public void setColSqlTime(final java.sql.Time colSqlTime) { + this.colSqlTime = colSqlTime; + } + + public java.sql.Timestamp getColSqlTimestamp() { + return colSqlTimestamp; + } + + public void setColSqlTimestamp(final java.sql.Timestamp colSqlTimestamp) { + this.colSqlTimestamp = colSqlTimestamp; + } + + public Optional getColStrOpt() { + return colStrOpt; + } + + public void setColStrOpt(final Optional colStrOpt) { + this.colStrOpt = colStrOpt; + } + + public Optional getColCharacterOpt() { + return colCharacterOpt; + } + + public void setColCharacterOpt(final Optional colCharacterOpt) { + this.colCharacterOpt = colCharacterOpt; + } + + public Optional getColShortTypeOpt() { + return colShortTypeOpt; + } + + public void setColShortTypeOpt(final Optional colShortTypeOpt) { + this.colShortTypeOpt = colShortTypeOpt; + } + + public Optional getColIntTypeOpt() { + return colIntTypeOpt; + } + + public void setColIntTypeOpt(final Optional colIntTypeOpt) { + this.colIntTypeOpt = colIntTypeOpt; + } + + public Optional getColLongTypeOpt() { + return colLongTypeOpt; + } + + public void setColLongTypeOpt(final Optional colLongTypeOpt) { + this.colLongTypeOpt = colLongTypeOpt; + } + + public Optional getColFloatTypeOpt() { + return colFloatTypeOpt; + } + + public void setColFloatTypeOpt(final Optional colFloatTypeOpt) { + this.colFloatTypeOpt = colFloatTypeOpt; + } + + public Optional getColDoubleTypeOpt() { + return colDoubleTypeOpt; + } + + public void setColDoubleTypeOpt(final Optional colDoubleTypeOpt) { + this.colDoubleTypeOpt = colDoubleTypeOpt; + } + + public Optional getColBigIntegerOpt() { + return colBigIntegerOpt; + } + + public void setColBigIntegerOpt(final Optional colBigIntegerOpt) { + this.colBigIntegerOpt = colBigIntegerOpt; + } + + public Optional getColBigDecimalOpt() { + return colBigDecimalOpt; + } + + public void setColBigDecimalOpt(final Optional colBigDecimalOpt) { + this.colBigDecimalOpt = colBigDecimalOpt; + } + + public Optional getColLocalDateOpt() { + return colLocalDateOpt; + } + + public void setColLocalDateOpt(final Optional colLocalDateOpt) { + this.colLocalDateOpt = colLocalDateOpt; + } + + public Optional getColLocalDateTimeOpt() { + return colLocalDateTimeOpt; + } + + public void setColLocalDateTimeOpt(final Optional colLocalDateTimeOpt) { + this.colLocalDateTimeOpt = colLocalDateTimeOpt; + } + + public Optional getColOffsetDateTimeOpt() { + return colOffsetDateTimeOpt; + } + + public void setColOffsetDateTimeOpt(final Optional colOffsetDateTimeOpt) { + this.colOffsetDateTimeOpt = colOffsetDateTimeOpt; + } + + public Optional getColZonedDateTimeOpt() { + return colZonedDateTimeOpt; + } + + public void setColZonedDateTimeOpt(final Optional colZonedDateTimeOpt) { + this.colZonedDateTimeOpt = colZonedDateTimeOpt; + } + + public Optional getColLocalTimeOpt() { + return colLocalTimeOpt; + } + + public void setColLocalTimeOpt(final Optional colLocalTimeOpt) { + this.colLocalTimeOpt = colLocalTimeOpt; + } + + public Optional getColOffsetTimeOpt() { + return colOffsetTimeOpt; + } + + public void setColOffsetTimeOpt(final Optional colOffsetTimeOpt) { + this.colOffsetTimeOpt = colOffsetTimeOpt; + } + + public Optional getColYearOpt() { + return colYearOpt; + } + + public void setColYearOpt(final Optional colYearOpt) { + this.colYearOpt = colYearOpt; + } + + public Optional getColYearMonthOpt() { + return colYearMonthOpt; + } + + public void setColYearMonthOpt(final Optional colYearMonthOpt) { + this.colYearMonthOpt = colYearMonthOpt; + } + + public Optional getColUtilDateOpt() { + return colUtilDateOpt; + } + + public void setColUtilDateOpt(final Optional colUtilDateOpt) { + this.colUtilDateOpt = colUtilDateOpt; + } + + public Optional getColSqlDateOpt() { + return colSqlDateOpt; + } + + public void setColSqlDateOpt(final Optional colSqlDateOpt) { + this.colSqlDateOpt = colSqlDateOpt; + } + + public Optional getColSqlTimeOpt() { + return colSqlTimeOpt; + } + + public void setColSqlTimeOpt(final Optional colSqlTimeOpt) { + this.colSqlTimeOpt = colSqlTimeOpt; + } + + public Optional getColSqlTimestampOpt() { + return colSqlTimestampOpt; + } + + public void setColSqlTimestampOpt(final Optional colSqlTimestampOpt) { + this.colSqlTimestampOpt = colSqlTimestampOpt; + } + + public String[] getColStrArr() { + return colStrArr; + } + + public void setColStrArr(final String[] colStrArr) { + this.colStrArr = colStrArr; + } + + public char[] getColCharArr() { + return colCharArr; + } + + public void setColCharArr(final char[] colCharArr) { + this.colCharArr = colCharArr; + } + + public Character[] getColCharacterArr() { + return colCharacterArr; + } + + public void setColCharacterArr(final Character[] colCharacterArr) { + this.colCharacterArr = colCharacterArr; + } + + public short[] getColShortArr() { + return colShortArr; + } + + public void setColShortArr(final short[] colShortArr) { + this.colShortArr = colShortArr; + } + + public Short[] getColShortTypeArr() { + return colShortTypeArr; + } + + public void setColShortTypeArr(final Short[] colShortTypeArr) { + this.colShortTypeArr = colShortTypeArr; + } + + public int[] getColIntArr() { + return colIntArr; + } + + public void setColIntArr(final int[] colIntArr) { + this.colIntArr = colIntArr; + } + + public Integer[] getColIntTypeArr() { + return colIntTypeArr; + } + + public void setColIntTypeArr(final Integer[] colIntTypeArr) { + this.colIntTypeArr = colIntTypeArr; + } + + public long[] getColLongArr() { + return colLongArr; + } + + public void setColLongArr(final long[] colLongArr) { + this.colLongArr = colLongArr; + } + + public Long[] getColLongTypeArr() { + return colLongTypeArr; + } + + public void setColLongTypeArr(final Long[] colLongTypeArr) { + this.colLongTypeArr = colLongTypeArr; + } + + public float[] getColFloatArr() { + return colFloatArr; + } + + public void setColFloatArr(final float[] colFloatArr) { + this.colFloatArr = colFloatArr; + } + + public Float[] getColFloatTypeArr() { + return colFloatTypeArr; + } + + public void setColFloatTypeArr(final Float[] colFloatTypeArr) { + this.colFloatTypeArr = colFloatTypeArr; + } + + public double[] getColDoubleArr() { + return colDoubleArr; + } + + public void setColDoubleArr(final double[] colDoubleArr) { + this.colDoubleArr = colDoubleArr; + } + + public Double[] getColDoubleTypeArr() { + return colDoubleTypeArr; + } + + public void setColDoubleTypeArr(final Double[] colDoubleTypeArr) { + this.colDoubleTypeArr = colDoubleTypeArr; + } + + public BigInteger[] getColBigIntegerArr() { + return colBigIntegerArr; + } + + public void setColBigIntegerArr(final BigInteger[] colBigIntegerArr) { + this.colBigIntegerArr = colBigIntegerArr; + } + + public BigDecimal[] getColBigDecimalArr() { + return colBigDecimalArr; + } + + public void setColBigDecimalArr(final BigDecimal[] colBigDecimalArr) { + this.colBigDecimalArr = colBigDecimalArr; + } + + public LocalDate[] getColLocalDateArr() { + return colLocalDateArr; + } + + public void setColLocalDateArr(final LocalDate[] colLocalDateArr) { + this.colLocalDateArr = colLocalDateArr; + } + + public LocalDateTime[] getColLocalDateTimeArr() { + return colLocalDateTimeArr; + } + + public void setColLocalDateTimeArr(final LocalDateTime[] colLocalDateTimeArr) { + this.colLocalDateTimeArr = colLocalDateTimeArr; + } + + public OffsetDateTime[] getColOffsetDateTimeArr() { + return colOffsetDateTimeArr; + } + + public void setColOffsetDateTimeArr(final OffsetDateTime[] colOffsetDateTimeArr) { + this.colOffsetDateTimeArr = colOffsetDateTimeArr; + } + + public ZonedDateTime[] getColZonedDateTimeArr() { + return colZonedDateTimeArr; + } + + public void setColZonedDateTimeArr(final ZonedDateTime[] colZonedDateTimeArr) { + this.colZonedDateTimeArr = colZonedDateTimeArr; + } + + public LocalTime[] getColLocalTimeArr() { + return colLocalTimeArr; + } + + public void setColLocalTimeArr(final LocalTime[] colLocalTimeArr) { + this.colLocalTimeArr = colLocalTimeArr; + } + + public OffsetTime[] getColOffsetTimeArr() { + return colOffsetTimeArr; + } + + public void setColOffsetTimeArr(final OffsetTime[] colOffsetTimeArr) { + this.colOffsetTimeArr = colOffsetTimeArr; + } + + public Year[] getColYearArr() { + return colYearArr; + } + + public void setColYearArr(final Year[] colYearArr) { + this.colYearArr = colYearArr; + } + + public YearMonth[] getColYearMonthArr() { + return colYearMonthArr; + } + + public void setColYearMonthArr(final YearMonth[] colYearMonthArr) { + this.colYearMonthArr = colYearMonthArr; + } + + public java.util.Date[] getColUtilDateArr() { + return colUtilDateArr; + } + + public void setColUtilDateArr(final java.util.Date[] colUtilDateArr) { + this.colUtilDateArr = colUtilDateArr; + } + + public java.sql.Date[] getColSqlDateArr() { + return colSqlDateArr; + } + + public void setColSqlDateArr(final java.sql.Date[] colSqlDateArr) { + this.colSqlDateArr = colSqlDateArr; + } + + public java.sql.Time[] getColSqlTimeArr() { + return colSqlTimeArr; + } + + public void setColSqlTimeArr(final java.sql.Time[] colSqlTimeArr) { + this.colSqlTimeArr = colSqlTimeArr; + } + + public java.sql.Timestamp[] getColSqlTimestampArr() { + return colSqlTimestampArr; + } + + public void setColSqlTimestampArr(final java.sql.Timestamp[] colSqlTimestampArr) { + this.colSqlTimestampArr = colSqlTimestampArr; + } + + } +} diff --git a/src/test/java/jp/co/future/uroborosql/mapping/TestEntity4.java b/src/test/java/jp/co/future/uroborosql/mapping/TestEntity4.java new file mode 100644 index 00000000..5847d1e9 --- /dev/null +++ b/src/test/java/jp/co/future/uroborosql/mapping/TestEntity4.java @@ -0,0 +1,124 @@ +package jp.co.future.uroborosql.mapping; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.Objects; + +import jp.co.future.uroborosql.mapping.annotations.Table; +import jp.co.future.uroborosql.mapping.annotations.Version; + +@Table(name = "TEST") +public class TestEntity4 { + private Long id; + private String name; + private BigDecimal age; + private LocalDate birthday; + @Version + private Integer lockVersion = 0; + + public TestEntity4() { + } + + public TestEntity4(final Long id, final String name, final BigDecimal age, final LocalDate birthday) { + this.id = id; + this.name = name; + this.age = age; + this.birthday = birthday; + } + + public interface Names { + String Id = "id"; + String Name = "name"; + String Age = "age"; + String Birthday = "birthday"; + } + + public interface Cols { + String Id = "id"; + String Name = "name"; + String Age = "age"; + String Birthday = "birthday"; + } + + public Long getId() { + return this.id; + } + + public String getName() { + return this.name; + } + + public BigDecimal getAge() { + return this.age; + } + + public LocalDate getBirthday() { + return this.birthday; + } + + public void setId(final Long id) { + this.id = id; + } + + public void setName(final String name) { + this.name = name; + } + + public void setAge(final BigDecimal age) { + this.age = age; + } + + public void setBirthday(final LocalDate birthday) { + this.birthday = birthday; + } + + public Integer getLockVersion() { + return lockVersion; + } + + public void setLockVersion(final Integer lockVersion) { + this.lockVersion = lockVersion; + } + + @Override + public int hashCode() { + return Objects.hash(age, birthday, id, lockVersion, name); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + var other = (TestEntity4) obj; + if (!Objects.equals(age, other.age)) { + return false; + } + if (!Objects.equals(birthday, other.birthday)) { + return false; + } + if (!Objects.equals(id, other.id)) { + return false; + } + if (!Objects.equals(lockVersion, other.lockVersion)) { + return false; + } + if (!Objects.equals(name, other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "TestEntity4 [id=" + id + ", name=" + name + ", age=" + age + ", birthday=" + birthday + ", lockVersion=" + + lockVersion + "]"; + } + +} \ No newline at end of file diff --git a/src/test/java/jp/co/future/uroborosql/mapping/TestEntity5.java b/src/test/java/jp/co/future/uroborosql/mapping/TestEntity5.java new file mode 100644 index 00000000..5ae39d4d --- /dev/null +++ b/src/test/java/jp/co/future/uroborosql/mapping/TestEntity5.java @@ -0,0 +1,125 @@ +package jp.co.future.uroborosql.mapping; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.Objects; +import java.util.Optional; + +import jp.co.future.uroborosql.mapping.annotations.Table; +import jp.co.future.uroborosql.mapping.annotations.Version; + +@Table(name = "TEST") +public class TestEntity5 { + private Long id; + private String name; + private Optional age; + private LocalDate birthday; + @Version + private Integer lockVersion = 0; + + public TestEntity5() { + } + + public TestEntity5(final Long id, final String name, final Optional age, final LocalDate birthday) { + this.id = id; + this.name = name; + this.age = age; + this.birthday = birthday; + } + + public interface Names { + String Id = "id"; + String Name = "name"; + String Age = "age"; + String Birthday = "birthday"; + } + + public interface Cols { + String Id = "id"; + String Name = "name"; + String Age = "age"; + String Birthday = "birthday"; + } + + public Long getId() { + return this.id; + } + + public String getName() { + return this.name; + } + + public Optional getAge() { + return this.age; + } + + public LocalDate getBirthday() { + return this.birthday; + } + + public void setId(final Long id) { + this.id = id; + } + + public void setName(final String name) { + this.name = name; + } + + public void setAge(final Optional age) { + this.age = age; + } + + public void setBirthday(final LocalDate birthday) { + this.birthday = birthday; + } + + public Integer getLockVersion() { + return lockVersion; + } + + public void setLockVersion(final Integer lockVersion) { + this.lockVersion = lockVersion; + } + + @Override + public int hashCode() { + return Objects.hash(age, birthday, id, lockVersion, name); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + var other = (TestEntity5) obj; + if (!Objects.equals(age, other.age)) { + return false; + } + if (!Objects.equals(birthday, other.birthday)) { + return false; + } + if (!Objects.equals(id, other.id)) { + return false; + } + if (!Objects.equals(lockVersion, other.lockVersion)) { + return false; + } + if (!Objects.equals(name, other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "TestEntity5 [id=" + id + ", name=" + name + ", age=" + age + ", birthday=" + birthday + ", lockVersion=" + + lockVersion + "]"; + } + +} \ No newline at end of file diff --git a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteBatchEvent.txt b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteBatchEvent.txt index eec87717..c6d6f130 100644 --- a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteBatchEvent.txt +++ b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteBatchEvent.txt @@ -1 +1 @@ -{"userName":"testUserName","funcId":"testFunction","sqlId":"333","sqlName":"example\/insert_product","sql":"INSERT INTO \tPRODUCT ( \tPRODUCT_ID ,\tPRODUCT_NAME ,\tPRODUCT_KANA_NAME ,\tJAN_CODE ,\tPRODUCT_DESCRIPTION ,\tINS_DATETIME ,\tUPD_DATETIME ,\tVERSION_NO ) VALUES ( \t?\/*product_id*\/ ,\t?\/*product_name*\/ ,\t?\/*product_kana_name*\/ ,\t?\/*jan_code*\/ ,\t?\/*product_description*\/ ,\t?\/*ins_datetime*\/ ,\t?\/*upd_datetime*\/ ,\t?\/*version_no*\/ )","rowCount":1} \ No newline at end of file +AuditData: {"userName":"testUserName","funcId":"testFunction","sqlId":"333","sqlName":"example\/insert_product","sql":"INSERT INTO \tPRODUCT ( \tPRODUCT_ID ,\tPRODUCT_NAME ,\tPRODUCT_KANA_NAME ,\tJAN_CODE ,\tPRODUCT_DESCRIPTION ,\tINS_DATETIME ,\tUPD_DATETIME ,\tVERSION_NO ) VALUES ( \t?\/*product_id*\/ ,\t?\/*product_name*\/ ,\t?\/*product_kana_name*\/ ,\t?\/*jan_code*\/ ,\t?\/*product_description*\/ ,\t?\/*ins_datetime*\/ ,\t?\/*upd_datetime*\/ ,\t?\/*version_no*\/ )","rowCount":1} \ No newline at end of file diff --git a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEvent.txt b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEvent.txt index 6c86be39..4534b342 100644 --- a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEvent.txt +++ b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEvent.txt @@ -1 +1 @@ -{"userName":"testUserName","funcId":"testFunction","sqlId":"111","sqlName":"example\/select_product","sql":"SELECT \/* 111 *\/ \t* FROM \tPRODUCT WHERE 1 = 1 AND\tPRODUCT_ID\tIN\t(?, ?)\/*product_id*\/ ORDER BY PRODUCT_ID","rowCount":1} \ No newline at end of file +AuditData: {"userName":"testUserName","funcId":"testFunction","sqlId":"111","sqlName":"example\/select_product","sql":"SELECT \/* 111 *\/ \t* FROM \tPRODUCT WHERE 1 = 1 AND\tPRODUCT_ID\tIN\t(?, ?)\/*product_id*\/ ORDER BY PRODUCT_ID","rowCount":1} \ No newline at end of file diff --git a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEventCustomParam.txt b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEventCustomParam.txt index 301f6fa9..bc63ca38 100644 --- a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEventCustomParam.txt +++ b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteQueryEventCustomParam.txt @@ -1 +1 @@ -{"userName":"testUserName2","funcId":"testFunction2","sqlId":"111","sqlName":"example\/select_product","sql":"SELECT \/* 111 *\/ \t* FROM \tPRODUCT WHERE 1 = 1 AND\tPRODUCT_ID\tIN\t(?, ?)\/*product_id*\/ ORDER BY PRODUCT_ID","rowCount":1} \ No newline at end of file +AuditData: {"userName":"testUserName2","funcId":"testFunction2","sqlId":"111","sqlName":"example\/select_product","sql":"SELECT \/* 111 *\/ \t* FROM \tPRODUCT WHERE 1 = 1 AND\tPRODUCT_ID\tIN\t(?, ?)\/*product_id*\/ ORDER BY PRODUCT_ID","rowCount":1} \ No newline at end of file diff --git a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteUpdateEvent.txt b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteUpdateEvent.txt index 8d02cd5c..1bd02869 100644 --- a/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteUpdateEvent.txt +++ b/src/test/resources/data/expected/AuditLogEventSubscriber/testExecuteUpdateEvent.txt @@ -1 +1 @@ -{"userName":"testUserName","funcId":"testFunction","sqlId":"222","sqlName":"example\/selectinsert_product","sql":"insert into product ( product_id , product_name , product_kana_name , jan_code , product_description , ins_datetime , upd_datetime , version_no ) select ?\/*product_id*\/ , product_name , product_kana_name , jan_code , product_description , ins_datetime , ins_datetime , 0 from product_regist_work where jan_code = ?\/*jan_code*\/","rowCount":1} \ No newline at end of file +AuditData: {"userName":"testUserName","funcId":"testFunction","sqlId":"222","sqlName":"example\/selectinsert_product","sql":"insert into product ( product_id , product_name , product_kana_name , jan_code , product_description , ins_datetime , upd_datetime , version_no ) select ?\/*product_id*\/ , product_name , product_kana_name , jan_code , product_description , ins_datetime , ins_datetime , 0 from product_regist_work where jan_code = ?\/*jan_code*\/","rowCount":1} \ No newline at end of file diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index eea872de..d6027325 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -6,7 +6,8 @@ System.out - %-40.40logger - [%.-1level] - %m%n + + %m%n @@ -32,31 +33,28 @@ - - - - - - - - + + + + + - +