DatabaseImpl implements Database { @Override public <T> Optional<T> selectOne(String sql, Class<T> viewClass, Object... params) { validateAsterisk(sql); validateStringValue(sql); var watch = new StopWatch(); int returnedRows = 0; try { Optional<T> result = operation.selectOne(sql, rowMapper(viewClass), params); if (result.isPresent()) returnedRows = 1; return result; } finally { long elapsed = watch.elapsed(); int operations = ActionLogContext.track("db", elapsed, returnedRows, 0); logger.debug("selectOne, sql={}, params={}, returnedRows={}, elapsed={}", sql, new SQLParams(operation.enumMapper, params), returnedRows, elapsed); checkOperation(elapsed, operations); } } DatabaseImpl(String name); void close(); void timeout(Duration timeout); void url(String url); void view(Class<T> viewClass); Repository<T> repository(Class<T> entityClass); @Override Transaction beginTransaction(); @Override List<T> select(String sql, Class<T> viewClass, Object... params); @Override Optional<T> selectOne(String sql, Class<T> viewClass, Object... params); @Override int execute(String sql, Object... params); @Override int[] batchExecute(String sql, List<Object[]> params); final Pool<Connection> pool; final DatabaseOperation operation; public String user; public String password; public int maxOperations; public int tooManyRowsReturnedThreshold; public long slowOperationThresholdInNanos; public IsolationLevel isolationLevel; }
@Test void selectOneWithView() { insertRow(1, "string1", TestEnum.V1); EntityView view = database.selectOne("SELECT string_field as string_label, enum_field as enum_label FROM database_test where id = ?", EntityView.class, 1).orElseThrow(); assertThat(view.enumField).isEqualTo(TestEnum.V1); assertThat(view.stringField).isEqualTo("string1"); }
@Test void selectNullInt() { Optional<Integer> result = database.selectOne("SELECT max(id) FROM database_test", Integer.class); assertThat(result).isNotPresent(); }
@Test void selectNumber() { assertThat(database.selectOne("SELECT count(id) FROM database_test", Integer.class)).get().isEqualTo(0); assertThat(database.selectOne("SELECT count(id) FROM database_test", Long.class)).get().isEqualTo(0L); assertThat(database.selectOne("SELECT count(id) FROM database_test", Double.class)).get().isEqualTo(0.0); assertThat(database.selectOne("SELECT count(id) FROM database_test", BigDecimal.class)).get().isEqualTo(BigDecimal.ZERO); }
@Test void selectString() { insertRow(1, "string1", TestEnum.V1); Optional<String> result = database.selectOne("SELECT string_field FROM database_test", String.class); assertThat(result).get().isEqualTo("string1"); }