forked from plusone/plusone-commons
修改类名,同时支持事务。
parent
5bd676578b
commit
95f625d849
|
@ -35,24 +35,25 @@ import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
|
||||||
import com.google.common.annotations.Beta;
|
import com.google.common.annotations.Beta;
|
||||||
|
|
||||||
import xyz.zhouxy.plusone.commons.util.MoreCollections;
|
import xyz.zhouxy.plusone.commons.util.Assert;
|
||||||
|
import xyz.zhouxy.plusone.commons.util.OptionalUtil;
|
||||||
|
|
||||||
@Beta
|
@Beta
|
||||||
public class JdbcUtil {
|
public class SimpleJdbcTemplate {
|
||||||
|
|
||||||
public static JdbcExecutor connect(Connection conn) {
|
public static JdbcExecutorBak connect(final Connection conn) {
|
||||||
return new JdbcExecutor(conn);
|
return new JdbcExecutorBak(conn);
|
||||||
}
|
}
|
||||||
|
|
||||||
private JdbcUtil() {
|
private SimpleJdbcTemplate() {
|
||||||
throw new IllegalStateException("Utility class");
|
throw new IllegalStateException("Utility class");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class JdbcExecutor {
|
public static class JdbcExecutorBak {
|
||||||
|
|
||||||
private final Connection conn;
|
private final Connection conn;
|
||||||
|
|
||||||
public JdbcExecutor(Connection conn) {
|
public JdbcExecutorBak(Connection conn) {
|
||||||
this.conn = conn;
|
this.conn = conn;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -74,6 +75,11 @@ public class JdbcUtil {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public <T> Optional<T> queryFirst(String sql, Object[] params, ResultMap<T> resultMap) throws SQLException {
|
||||||
|
List<T> list = query(sql, params, resultMap);
|
||||||
|
return (list.isEmpty()) ? Optional.empty() : Optional.ofNullable(list.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
public static final ResultMap<Map<String, Object>> mapResultMap = rs -> {
|
public static final ResultMap<Map<String, Object>> mapResultMap = rs -> {
|
||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
ResultSetMetaData metaData = rs.getMetaData();
|
ResultSetMetaData metaData = rs.getMetaData();
|
||||||
|
@ -89,6 +95,10 @@ public class JdbcUtil {
|
||||||
return query(sql, params, mapResultMap);
|
return query(sql, params, mapResultMap);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Optional<Map<String, Object>> queryFirst(String sql, Object... params) throws SQLException {
|
||||||
|
return queryFirst(sql, params, mapResultMap);
|
||||||
|
}
|
||||||
|
|
||||||
public static final ResultMap<DbRecord> recordResultMap = rs -> {
|
public static final ResultMap<DbRecord> recordResultMap = rs -> {
|
||||||
DbRecord result = new DbRecord();
|
DbRecord result = new DbRecord();
|
||||||
ResultSetMetaData metaData = rs.getMetaData();
|
ResultSetMetaData metaData = rs.getMetaData();
|
||||||
|
@ -104,26 +114,26 @@ public class JdbcUtil {
|
||||||
return query(sql, params, recordResultMap);
|
return query(sql, params, recordResultMap);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Optional<DbRecord> queryFirstRecord(String sql, Object... params) throws SQLException {
|
||||||
|
return queryFirst(sql, params, recordResultMap);
|
||||||
|
}
|
||||||
|
|
||||||
public Optional<String> queryToString(String sql, Object... params) throws SQLException {
|
public Optional<String> queryToString(String sql, Object... params) throws SQLException {
|
||||||
List<String> result = query(sql, params, (ResultSet rs) -> rs.getString(1));
|
return queryFirst(sql, params, (ResultSet rs) -> rs.getString(1));
|
||||||
return MoreCollections.isNotEmpty(result) ? Optional.ofNullable(result.get(0)) : Optional.empty();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public OptionalInt queryToInt(String sql, Object... params) throws SQLException {
|
public OptionalInt queryToInt(String sql, Object... params) throws SQLException {
|
||||||
List<Integer> result = query(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).intValue());
|
Optional<Integer> result = queryFirst(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).intValue());
|
||||||
Integer i = MoreCollections.isNotEmpty(result) ? result.get(0) : null;
|
return OptionalUtil.toOptionalInt(result);
|
||||||
return i != null ? OptionalInt.of(i) : OptionalInt.empty();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public OptionalLong queryToLong(String sql, Object... params) throws SQLException {
|
public OptionalLong queryToLong(String sql, Object... params) throws SQLException {
|
||||||
List<Long> result = query(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).longValue());
|
Optional<Long> result = queryFirst(sql, params, (ResultSet rs) -> rs.getBigDecimal(1).longValue());
|
||||||
Long i = MoreCollections.isNotEmpty(result) ? result.get(0) : null;
|
return OptionalUtil.toOptionalLong(result);
|
||||||
return i != null ? OptionalLong.of(i) : OptionalLong.empty();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<BigDecimal> queryToBigDecimal(String sql, Object... params) throws SQLException {
|
public Optional<BigDecimal> queryToBigDecimal(String sql, Object... params) throws SQLException {
|
||||||
List<BigDecimal> result = query(sql, params, (ResultSet rs) -> rs.getBigDecimal(1));
|
return queryFirst(sql, params, (ResultSet rs) -> rs.getBigDecimal(1));
|
||||||
return MoreCollections.isNotEmpty(result) ? Optional.ofNullable(result.get(0)) : Optional.empty();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int update(String sql, Object... params) throws SQLException {
|
public int update(String sql, Object... params) throws SQLException {
|
||||||
|
@ -156,5 +166,25 @@ public class JdbcUtil {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void tx(final Tx tx) throws Exception {
|
||||||
|
Assert.notNull(tx, "Tx can not be null.");
|
||||||
|
try {
|
||||||
|
this.conn.setAutoCommit(false);
|
||||||
|
tx.execute();
|
||||||
|
conn.commit();
|
||||||
|
conn.setAutoCommit(true);
|
||||||
|
} catch (Exception e) {
|
||||||
|
conn.rollback();
|
||||||
|
conn.setAutoCommit(true);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@FunctionalInterface
|
||||||
|
public static interface Tx {
|
||||||
|
@SuppressWarnings("all")
|
||||||
|
void execute() throws Exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,61 +0,0 @@
|
||||||
package xyz.zhouxy.plusone.commons.util;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.zaxxer.hikari.HikariConfig;
|
|
||||||
import com.zaxxer.hikari.HikariDataSource;
|
|
||||||
|
|
||||||
import xyz.zhouxy.plusone.commons.jdbc.DbRecord;
|
|
||||||
import xyz.zhouxy.plusone.commons.jdbc.JdbcUtil;
|
|
||||||
|
|
||||||
class JdbcUtilTests {
|
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(JdbcUtilTests.class);
|
|
||||||
|
|
||||||
static final String url = "jdbc:postgresql://localhost:5432/plusone";
|
|
||||||
static final String username = "postgres";
|
|
||||||
static final String password = "zhouxy108";
|
|
||||||
|
|
||||||
DataSource dataSource;
|
|
||||||
|
|
||||||
String[] cStruct = {
|
|
||||||
"id",
|
|
||||||
"created_by",
|
|
||||||
"create_time",
|
|
||||||
"updated_by",
|
|
||||||
"update_time",
|
|
||||||
"status"
|
|
||||||
};
|
|
||||||
|
|
||||||
JdbcUtilTests() {
|
|
||||||
HikariConfig config = new HikariConfig();
|
|
||||||
config.setJdbcUrl(url);
|
|
||||||
config.setUsername(username);
|
|
||||||
config.setPassword(password);
|
|
||||||
this.dataSource = new HikariDataSource(config);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testQuery() throws SQLException {
|
|
||||||
Connection conn = this.dataSource.getConnection();
|
|
||||||
List<DbRecord> rs = JdbcUtil.connect(conn).queryToRecordList(
|
|
||||||
"SELECT * FROM public.base_table WHERE id IN (?, ?, ?)", 501533, 501554, 544599);
|
|
||||||
assertTrue(3 > rs.size());
|
|
||||||
for (DbRecord baseEntity : rs) {
|
|
||||||
log.info("id: {}", baseEntity.getValueAsLong("id"));
|
|
||||||
assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -0,0 +1,123 @@
|
||||||
|
package xyz.zhouxy.plusone.commons.util;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.google.common.base.Splitter;
|
||||||
|
import com.google.common.io.Files;
|
||||||
|
import com.zaxxer.hikari.HikariConfig;
|
||||||
|
import com.zaxxer.hikari.HikariDataSource;
|
||||||
|
|
||||||
|
import xyz.zhouxy.plusone.commons.jdbc.DbRecord;
|
||||||
|
import xyz.zhouxy.plusone.commons.jdbc.SimpleJdbcTemplate;
|
||||||
|
|
||||||
|
class SimpleJdbcTemplateTests {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(SimpleJdbcTemplateTests.class);
|
||||||
|
|
||||||
|
DataSource dataSource;
|
||||||
|
|
||||||
|
String[] cStruct = {
|
||||||
|
"id",
|
||||||
|
"created_by",
|
||||||
|
"create_time",
|
||||||
|
"updated_by",
|
||||||
|
"update_time",
|
||||||
|
"status"
|
||||||
|
};
|
||||||
|
|
||||||
|
SimpleJdbcTemplateTests() {
|
||||||
|
HikariConfig config = new HikariConfig();
|
||||||
|
config.setJdbcUrl("jdbc:postgresql://localhost:5432/plusone");
|
||||||
|
config.setUsername("postgres");
|
||||||
|
config.setPassword("zhouxy108");
|
||||||
|
this.dataSource = new HikariDataSource(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testQuery() throws SQLException {
|
||||||
|
try (Connection conn = this.dataSource.getConnection()) {
|
||||||
|
List<DbRecord> rs = SimpleJdbcTemplate.connect(conn)
|
||||||
|
.queryToRecordList(
|
||||||
|
"SELECT * FROM public.base_table WHERE id IN (?, ?, ?)",
|
||||||
|
501533, 501554, 544599);
|
||||||
|
assertTrue(3 > rs.size());
|
||||||
|
for (DbRecord baseEntity : rs) {
|
||||||
|
log.info("id: {}", baseEntity.getValueAsLong("id"));
|
||||||
|
assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSaveTxt() throws IOException, SQLException {
|
||||||
|
File file = new File("C:\\Users\\zhouxy\\Desktop", "Untitled-1.txt");
|
||||||
|
assertTrue(file.exists());
|
||||||
|
List<String> recordStrList = Files.readLines(file, StandardCharsets.UTF_8);
|
||||||
|
if (MoreCollections.isEmpty(recordStrList)) {
|
||||||
|
log.info("file is empty.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<DbRecord> recordList = new ArrayList<>(recordStrList.size());
|
||||||
|
for (String rStr : recordStrList) {
|
||||||
|
List<String> props = Splitter.on("|").splitToList(rStr)
|
||||||
|
.stream()
|
||||||
|
.map(s -> {
|
||||||
|
if (s == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
s = s.trim();
|
||||||
|
return ("".equals(s) || "null".equals(s) || "NULL".equals(s)) ? null : s;
|
||||||
|
})
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
DbRecord r = new DbRecord();
|
||||||
|
for (int i = 0; i < cStruct.length; i++) {
|
||||||
|
r.put(cStruct[i], props.get(i));
|
||||||
|
}
|
||||||
|
recordList.add(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
final String sql = "INSERT INTO test_table(id, created_by, create_time, updated_by, update_time, status) VALUES(?, ?, ?, ?, ?, ?)";
|
||||||
|
final List<Object[]> params = recordList.stream()
|
||||||
|
.map(r -> new Object[] {
|
||||||
|
r.getValueAsString("id").orElse(null),
|
||||||
|
r.getValueAsString("created_by").orElse(null),
|
||||||
|
r.getValueAsString("create_time").orElse(null),
|
||||||
|
r.getValueAsString("updated_by").orElse(null),
|
||||||
|
r.getValueAsString("update_time").orElse(null),
|
||||||
|
r.getValueAsString("status").orElse(null)
|
||||||
|
})
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
try (Connection conn = this.dataSource.getConnection()) {
|
||||||
|
SimpleJdbcTemplate.connect(conn).tx(() -> {
|
||||||
|
SimpleJdbcTemplate.connect(conn).batchUpdate(sql, params, 20);
|
||||||
|
|
||||||
|
File targetFile = new File("C:\\Users\\zhouxy\\Desktop\\done", file.getName());
|
||||||
|
boolean moveSucceeded = file.renameTo(targetFile);
|
||||||
|
if (!moveSucceeded) {
|
||||||
|
throw new IOException("文件移动失败:" + file.getName());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (Exception e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue