Files
simple-jdbc/src/test/java/xyz/zhouxy/jdbc/SimpleJdbcTemplateTests.java

89 lines
2.9 KiB
Java
Raw Normal View History

2023-07-19 22:19:57 +08:00
package xyz.zhouxy.jdbc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static xyz.zhouxy.jdbc.SimpleJdbcTemplate.ParamBuilder.*;
import static xyz.zhouxy.plusone.commons.sql.JdbcSql.IN;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
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.sql.SQL;
class SimpleJdbcTemplateTests {
private static final Logger log = LoggerFactory.getLogger(SimpleJdbcTemplateTests.class);
2023-08-11 01:34:37 +08:00
private static final DataSource dataSource;
2023-07-19 22:19:57 +08:00
String[] cStruct = {
"id",
"created_by",
"create_time",
"updated_by",
"update_time",
"status"
};
2023-08-11 01:34:37 +08:00
static {
2023-07-19 22:19:57 +08:00
HikariConfig config = new HikariConfig();
2023-08-11 01:34:37 +08:00
config.setJdbcUrl("jdbc:postgresql://localhost:5432/jdbctest");
2023-07-19 22:19:57 +08:00
config.setUsername("postgres");
config.setPassword("zhouxy108");
2023-08-11 01:34:37 +08:00
config.setMaximumPoolSize(800);
config.setConnectionTimeout(1000000);
dataSource = new HikariDataSource(config);
2023-07-19 22:19:57 +08:00
}
@Test
void testQuery() throws SQLException {
2023-08-11 01:34:37 +08:00
try (Connection conn = dataSource.getConnection()) {
Object[] ids = buildParams("501533", "501554", "544599");
2023-07-19 22:19:57 +08:00
String sql = SQL.newJdbcSql()
.SELECT("*")
.FROM("test_table")
2023-08-11 01:34:37 +08:00
.WHERE(IN("id", ids))
2023-07-19 22:19:57 +08:00
.toString();
log.info(sql);
List<DbRecord> rs = SimpleJdbcTemplate.connect(conn)
2023-08-11 01:34:37 +08:00
.queryToRecordList(sql, ids);
2023-07-19 22:19:57 +08:00
assertNotNull(rs);
for (DbRecord baseEntity : rs) {
// log.info("id: {}", baseEntity.getValueAsString("id"));
log.info(baseEntity.toString());
assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
}
}
}
@Test
void testTransaction() {
try (Connection conn = dataSource.getConnection()) {
SimpleJdbcTemplate.connect(conn)
.tx(() -> {
SimpleJdbcTemplate.connect(conn)
.update("INSERT INTO base_table (created_by, create_time, status) VALUES (?, now(), 0)", 585757);
2023-08-11 01:34:37 +08:00
Optional<Map<String, Object>> first = SimpleJdbcTemplate.connect(conn)
2023-07-19 22:19:57 +08:00
.queryFirst("SELECT * FROM base_table WHERE created_by = ?", 585757);
log.info("first: {}", first);
throw new NullPointerException();
});
2023-08-11 01:34:37 +08:00
}
catch (Exception e) {
2023-07-19 22:19:57 +08:00
log.error(e.getMessage(), e);
}
}
}