快速操作数据库: 在 hutool 的基础上做了一些封装
好处: 免去了 mybatis/jpa 等库的各种学习成本,就是 SQL+ 变量
坏处: 可能只适合测试使用,不适合生产环境使用
下面是一些使用方式的介绍,从测试角度,大家看看这种方式时候测试人员使用吗?欢迎多给点建议
DataSourceSetting setting = DataSourceSetting.builder().
url("jdbc:postgresql://127.0.0.1:7432/test_hub?currentSchema=demo")
.driver("org.postgresql.Driver")
.username("postgres").password("changeit").build();
QuickDao dao = QuickDao.createDao("config/db.setting");
@Test
public void testQuery() {
var queryResult = dao.query("select * from hero");
for (Entity entity : queryResult) {
System.out.println(entity.keySet());
System.out.println(entity.values());
}
}
@Test
public void testQueryWithParameters() {
var queryResult = dao.query("select * from hero where name=?", "test");
for (Entity entity : queryResult) {
System.out.println(entity.keySet());
System.out.println(entity.values());
}
}
@Test
public void testQueryWithBindParams() {
Map<String, Object> params = MapUtil.builder("name", (Object) "test2").build();
var queryResult = dao.query("select * from hero where name=@name",
params);
for (Entity entity : queryResult) {
System.out.println(entity.keySet());
System.out.println(entity.values());
}
}
@Test
public void testSaveOrInsertEntity() {
Entity e = Entity.create("hero").set("name", "test4")
.set("secret_name", "100").set("age", 9000);
HeroDemoEntity demoEntity = new HeroDemoEntity();
demoEntity.setName("hero");
demoEntity.setAge(10);
demoEntity.setSecret_name("secret_name");
dao.saveOrUpdate(demoEntity,"hero");
dao.saveOrUpdate(e, "hero", "name", "secret_name"); //for upsert error
}
@Test
public void testExecute() {
int count = dao.execute("delete from hero where name='test2'");
System.out.println(count);
}
@Test
public void testDaoService() {
String connectConfig = "{\n" +
" \"url\" :\"jdbc:postgresql://127.0.0.1:7432/test_hub\",\n" +
" \"user\":\"postgres\",\n" +
" \"password\": \"changeit\"\n" +
"}";
SqlRequest request = SqlRequest.createRequest("select * from data_sources where name=@name");
String bindvalue = "{\n" +
"\"name\":\"本地测试环境\"\n" +
" }";
request.bindParameterValues(bindvalue);
request.dsConfig(connectConfig);
SqlService service = new SqlService();
SqlQueryResponse response = service.query(request);
System.out.println(JSONUtil.toJsonPrettyStr(response));
}