pureQuery 提供兩種編程風格:內聯方法 與 帶註解方法。內聯風格將 SQL 字串直接寫在 Java 代碼中,透過 Data 介面執行,優點在於:
PreparedStatement、資源關閉、結果集映射。RowHandler/ResultHandler。| 介面/類別 | 用途 |
|---|---|
DataFactory.getData(Connection) | 取得 Data 實例,入口點 |
data.update(sql, params...) | 單筆 INSERT/UPDATE/DELETE,回傳更新筆數 |
data.updateMany(sql, Collection) | 批次更新,回傳 int[] 各筆結果 |
data.queryList(sql, Bean.class, params) | 查詢映射為 List<Bean> |
data.queryIterator(sql, Bean.class, params) | 惰性載入 Iterator<Bean> |
data.queryArray(sql, Bean.class, params) | 回傳 Bean[] |
VALUES(?, ?, ?) + 位置參數VALUES(:name, :country) + pureQuery Bean / Map 自動對應屬性@Column、@Id、@GeneratedKey 註解微調。handle(ResultSet, T),適用複雜轉換或省略欄位。// 1. 使用 Bean,@GeneratedKey 欄位自動回填
Customer c = new Customer(...);
data.update(insertSql, c);
System.out.println(c.getCid()); // 自動生成的主鍵
// 2. 不用 Bean,指定回傳類型與欄位名
int key = data.update(insertSql, int.class, new String[]{"cid"}, params...);
Object[] arr = data.update(insertSql, Object[].class, new String[]{"cid"}, params...);
// arr[0] = generated key, arr[1] = update count
實作 Hook 介面,於建立 Data 時註冊:
Data db = DataFactory.getData(conn, new Hook() {
public void pre(String method, Data d, SqlStatementType type, Object... params) {
if (type == SqlStatementType.INSERT) {
Customer c = (Customer) params[0];
if (!allowedCountries.contains(c.getCountry()))
throw new DataRuntimeException("Country not allowed: " + c.getCountry());
}
}
public void post(String method, Data d, Object ret, SqlStatementType type, Object... params) {
// 記錄審計日誌、效能監控等
}
});
Customer Bean (含 @Id @GeneratedKey)。Data data = DataFactory.getData(conn);data.update("delete from customer"); 清空資料。List<Customer> list = data.queryList("select * from customer where country=?", Customer.class, "US");