ZhouXY108 2024-06-17 09:18:06 +08:00
commit b7751512ff
2 changed files with 62 additions and 26 deletions

View File

@ -42,8 +42,8 @@ import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import xyz.zhouxy.plusone.commons.util.MoreArrays; import xyz.zhouxy.plusone.commons.collection.CollectionTools;
import xyz.zhouxy.plusone.commons.util.MoreCollections; import xyz.zhouxy.plusone.commons.util.ArrayTools;
import xyz.zhouxy.plusone.commons.util.OptionalUtil; import xyz.zhouxy.plusone.commons.util.OptionalUtil;
@Beta @Beta
@ -107,8 +107,7 @@ public class SimpleJdbcTemplate {
} }
public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException { public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException {
List<T> list = query(sql, params, resultMap); return query(sql, params, resultMap).stream().findFirst();
return (list.isEmpty()) ? Optional.empty() : Optional.ofNullable(list.get(0));
} }
public static final ResultMap<Map<String, Object>> mapResultMap = (rs, rowNumber) -> { public static final ResultMap<Map<String, Object>> mapResultMap = (rs, rowNumber) -> {
@ -198,29 +197,30 @@ public class SimpleJdbcTemplate {
stmt.clearBatch(); stmt.clearBatch();
} }
} }
return MoreArrays.concatIntArray(result); return ArrayTools.concatIntArray(result);
} }
} }
public <T extends Exception> void tx(final IAtom<T> atom) throws SQLException, T { public <E extends Exception> void tx(final IAtom<E> atom) throws SQLException, E {
Preconditions.checkNotNull(atom, "Atom can not be null."); Preconditions.checkNotNull(atom, "Atom can not be null.");
final boolean autoCommit = this.conn.getAutoCommit();
try { try {
this.conn.setAutoCommit(false); this.conn.setAutoCommit(false);
atom.execute(); atom.execute(this);
conn.commit(); this.conn.commit();
conn.setAutoCommit(true);
} }
catch (Exception e) { catch (Exception e) {
conn.rollback(); this.conn.rollback();
conn.setAutoCommit(true);
throw e; throw e;
} }
finally {
this.conn.setAutoCommit(autoCommit);
}
} }
@FunctionalInterface @FunctionalInterface
public interface IAtom<T extends Exception> { public interface IAtom<E extends Exception> {
@SuppressWarnings("all") void execute(JdbcExecutor jdbcExecutor) throws SQLException, E;
void execute() throws SQLException, T;
} }
private static void fillStatement(PreparedStatement stmt, Object[] params) throws SQLException { private static void fillStatement(PreparedStatement stmt, Object[] params) throws SQLException {
@ -273,7 +273,7 @@ public class SimpleJdbcTemplate {
public static <T> List<Object[]> buildBatchParams(final Collection<T> c, final Function<T, Object[]> func) { public static <T> List<Object[]> buildBatchParams(final Collection<T> c, final Function<T, Object[]> func) {
Preconditions.checkNotNull(c, "The collection can not be null."); Preconditions.checkNotNull(c, "The collection can not be null.");
Preconditions.checkNotNull(func, "The func can not be null."); Preconditions.checkNotNull(func, "The func can not be null.");
if (MoreCollections.isEmpty(c)) { if (CollectionTools.isEmpty(c)) {
return Collections.emptyList(); return Collections.emptyList();
} }
return c.stream().map(func).collect(Collectors.toList()); return c.stream().map(func).collect(Collectors.toList());

View File

@ -2,11 +2,13 @@ package xyz.zhouxy.jdbc;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static xyz.zhouxy.jdbc.SimpleJdbcTemplate.ParamBuilder.*; import static xyz.zhouxy.jdbc.SimpleJdbcTemplate.ParamBuilder.*;
import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN; import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
@ -20,7 +22,10 @@ import org.slf4j.LoggerFactory;
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import xyz.zhouxy.jdbc.SimpleJdbcTemplate.JdbcExecutor;
import xyz.zhouxy.plusone.commons.sql.SQL; import xyz.zhouxy.plusone.commons.sql.SQL;
import xyz.zhouxy.plusone.commons.util.IdGenerator;
import xyz.zhouxy.plusone.commons.util.IdWorker;
class SimpleJdbcTemplateTests { class SimpleJdbcTemplateTests {
@ -39,7 +44,7 @@ class SimpleJdbcTemplateTests {
static { static {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/jdbctest"); config.setJdbcUrl("jdbc:postgresql://localhost:5432/plusone");
config.setUsername("postgres"); config.setUsername("postgres");
config.setPassword("zhouxy108"); config.setPassword("zhouxy108");
config.setMaximumPoolSize(800); config.setMaximumPoolSize(800);
@ -68,21 +73,52 @@ class SimpleJdbcTemplateTests {
} }
} }
final IdWorker idGenerator = IdGenerator.getSnowflakeIdGenerator(0);
@Test @Test
void testTransaction() { void testTransaction() throws SQLException {
try (Connection conn = dataSource.getConnection()) { try (Connection conn = dataSource.getConnection()) {
SimpleJdbcTemplate.connect(conn) long id = this.idGenerator.nextId();
.tx(() -> { JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn);
SimpleJdbcTemplate.connect(conn) try {
.update("INSERT INTO base_table (created_by, create_time, status) VALUES (?, now(), 0)", 585757); jdbcExecutor.tx(jdbc -> {
Optional<Map<String, Object>> first = SimpleJdbcTemplate.connect(conn) jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)",
.queryFirst("SELECT * FROM base_table WHERE created_by = ?", 585757); buildParams(id, 585757, LocalDateTime.now(), 0));
log.info("first: {}", first);
throw new NullPointerException(); throw new NullPointerException();
}); });
}
catch (NullPointerException e) {
// ignore
}
catch (Exception e) {
e.printStackTrace();
}
Optional<Map<String, Object>> first = jdbcExecutor
.queryFirst("SELECT * FROM base_table WHERE id = ?", id);
log.info("first: {}", first);
assertTrue(!first.isPresent());
} }
catch (Exception e) {
log.error(e.getMessage(), e); try (Connection conn = dataSource.getConnection()) {
long id = this.idGenerator.nextId();
JdbcExecutor jdbcExecutor = SimpleJdbcTemplate.connect(conn);
try {
jdbcExecutor.tx(jdbc -> {
jdbc.update("INSERT INTO base_table (id, created_by, create_time, status) VALUES (?, ?, ?, ?)",
buildParams(id, 585757, LocalDateTime.now(), 0));
// throw new NullPointerException();
});
}
catch (NullPointerException e) {
// ignore
}
catch (Exception e) {
e.printStackTrace();
}
Optional<Map<String, Object>> first = jdbcExecutor
.queryFirst("SELECT * FROM base_table WHERE id = ?", id);
log.info("first: {}", first);
assertTrue(first.isPresent());
} }
} }
} }