Java連接數據庫 #04# Apache Commons DbUtils
索引
- 通過一個簡單的調用看整體結構
- Examples
- 修改JAVA連接數據庫 #03# HikariCP中的代碼
DbUtils並非是什麽ORM框架,只是對原始的JDBC進行了一些封裝,以便我們少寫一些重復代碼。就“用”而言,僅僅需要學習QueryRunner類和ResultSetHandler接口就可以了。它的顯著特點就是超級輕量級,總代碼量目測似乎還不到一萬行。
通過一個簡單的調用看整體結構
public class TestDbUtils { private static final QueryRunner RUNNER = newTestDbUtils.javaQueryRunner(HikariCPUtils.getDs()); public static void main(String[] args) { ResultSetHandler<SimpleUser> handler = new BeanHandler<>(SimpleUser.class); SimpleUser user = null; try { user = RUNNER.query("SELECT * FROM simple_user WHERE username=?", handler, "admin123"); }catch (SQLException e) { e.printStackTrace(); } System.out.println(user); } }
/** * Calls query after checking the parameters to ensure nothing is null. * @param conn The connection to use for the query call. * @paramprivate T query(Connection conn, boolean closeConn, String sql, ResultSetHandler rsh, Object... params) throws SQLExceptioncloseConn True if the connection should be closed, false otherwise. * @param sql The SQL statement to execute. * @param params An array of query replacement parameters. Each row in * this array is one set of batch replacement values. * @return The results of the query. * @throws SQLException If there are database or parameter errors. */ private <T> T query(Connection conn, boolean closeConn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } if (rsh == null) { if (closeConn) { close(conn); } throw new SQLException("Null ResultSetHandler"); } PreparedStatement stmt = null; ResultSet rs = null; T result = null; try { stmt = this.prepareStatement(conn, sql); this.fillStatement(stmt, params); rs = this.wrap(stmt.executeQuery()); result = rsh.handle(rs); } catch (SQLException e) { this.rethrow(e, sql, params); } finally { try { close(rs); } finally { close(stmt); if (closeConn) { close(conn); } } } return result; }
AbstractQueryRunner、RowProcessor、ResultSetHandler<T>是Apache Commons DbUtils裏的三大主角,通過繼承上述抽象類/實現上述接口可以很方便地對API功能進行定制化。另外,想用好DbUtils的話,感覺QueryRunner類和DbUtils類的源碼應該是需要經常參照的,通過這兩個類可以完成大部分事情,並且靈活度很高。
詳細類圖參考:http://ju.outofmemory.cn/entry/143920
Examples
官方Examples:http://commons.apache.org/proper/commons-dbutils/examples.html
同步請求的代碼在上面已經給出。異步請求的草稿代碼如下:
public class DbUtilsSampleDAO { private AsyncQueryRunner runner = new AsyncQueryRunner(Executors.newCachedThreadPool()); public Future<Integer> saveProfile(Profile profile) { Future<Integer> future; Connection conn = null; try { conn = ConnectionFactory.getConnection(); future = runner.update(conn, "INSERT ignore INTO `profiles`.`profile` (`username`, `password`, `nickname`) " + "VALUES (?, ?, ?)", profile.getUsername(), profile.getPassword(), profile.getNickname()); } catch (SQLException e) { throw new DaoException(e); } finally { try { DbUtils.close(conn); } catch (SQLException e) { throw new DaoException(e); } } return future; } public static void main(String[] args) { DbUtilsSampleDAO dao = new DbUtilsSampleDAO(); Profile profile = new Profile("myusername", "mypassword", "thisnickname"); Future<Integer> future = dao.saveProfile(profile); try { System.out.println(future.get() == 1 ? "更新成功" : "更新失敗"); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
修改JAVA連接數據庫 #03# HikariCP中的代碼
同步更新在GitHub:https://github.com/xkfx/web-test-01
主要的幾個類如下:
① QueryRunnerProxy.java
package org.sample.webapp.db.queryrunner; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.sample.webapp.db.connmanager.ConnectionFactory; import org.sample.webapp.exception.DaoException; import java.sql.SQLException; /** * 封裝DAO層通用代碼,不會關閉connection!!! */ public class QueryRunnerProxy { private QueryRunnerProxy() { // Exists to defeat instantiation } private static QueryRunner runner = new QueryRunner(); public static int update(String sql, Object... param) { int updates = 0; try { updates = runner.update(ConnectionFactory.getConnection(), sql, param); } catch (SQLException e) { throw new DaoException(e); } return updates; } public static <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) { T result = null; try { result = runner.query(ConnectionFactory.getConnection(), sql, rsh, params); } catch (SQLException e) { throw new DaoException(e); } return result; } }
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
② RsHandlers.java
package org.sample.webapp.db.queryrunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.sample.webapp.entity.Profile; /** * 業務相關,保存各式各樣的ResultSetHandler常量 */ public interface RsHandlers { BeanListHandler<Profile> PROFILE_LIST = new BeanListHandler<>(Profile.class); BeanHandler<Profile> PROFILE = new BeanHandler<>(Profile.class); }
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
③ ProfileDAOImpl.java 順便改為enum了,僅是因為感覺這樣寫表示單例更清晰。
package org.sample.webapp.dao.impl; import org.sample.webapp.dao.ProfileDAO; import org.sample.webapp.db.queryrunner.QueryRunnerProxy; import org.sample.webapp.db.queryrunner.RsHandlers; import org.sample.webapp.entity.Profile; import java.util.List; /** * 該類方法統一拋出DaoException */ public enum ProfileDAOImpl implements ProfileDAO { INSTANCE; @Override public int saveProfile(Profile profile) { final String sql = "INSERT ignore INTO profile (username, password, nickname) " + "VALUES (?, ?, ?)"; // 添加ignore出現重復不會拋出異常而是返回0 return QueryRunnerProxy.update(sql, profile.getUsername(), profile.getPassword(), profile.getNickname()); } @Override public List<Profile> listByNickname(String nickname) { final String sql = "SELECT profile_id AS id, username, password, nickname, last_online AS lastOnline, gender, birthday, location, joined " + "FROM profile " + "WHERE nickname=?"; return QueryRunnerProxy.query(sql, RsHandlers.PROFILE_LIST, nickname); } @Override public Profile getByUsername(String username) { final String sql = "SELECT profile_id AS id, username, password, nickname, last_online AS lastOnline, gender, birthday, location, joined " + "FROM profile " + "WHERE username=?"; // TODO 該字符串會反復創建嗎? return QueryRunnerProxy.query(sql, RsHandlers.PROFILE, username); } @Override public int updateById(Profile profile) { final String sql = "UPDATE profile " + "SET nickname=?, gender=?, birthday=?, location=? " + "WHERE profile_id=?"; return QueryRunnerProxy.update(sql, profile.getNickname(), profile.getGender() != null ? String.valueOf(profile.getGender()) : null, profile.getBirthday(), profile.getLocation(), profile.getId()); } @Override public int updatePassword(String username, String password) { final String sql = "UPDATE profile " + "SET password=? " + "WHERE username=?"; return QueryRunnerProxy.update(sql, password, username); } @Override public int updateLastOnline(String username) { final String sql = "UPDATE profile " + "SET last_online=CURRENT_TIMESTAMP " + "WHERE username=?"; return QueryRunnerProxy.update(sql, username); } }
Java連接數據庫 #04# Apache Commons DbUtils