DAO (Data Access Object) 模式將資料存取邏輯封裝,實現業務邏輯與持久化技術解耦。本文以 MySQL 為例,展示從驅動載入、連線池工具、實體類、DAO 介面到工廠模式的完整分層實作。
Class.forName("com.mysql.jdbc.Driver")DriverManager.getConnection(url, user, pwd)Connection.createStatement() 或 prepareStatement()ResultSetpublic class ConnectionUtils {
private static ThreadLocal<Connection> tl = new ThreadLocal<>();
private static String url, driver, username, password;
static {
// 載入屬性檔、註冊驅動
Properties props = new Properties();
props.load(ConnectionUtils.class.getClassLoader()
.getResourceAsStream("com/day03/db_mysql.properties"));
url = props.getProperty("url");
driver = props.getProperty("driver");
username = props.getProperty("username");
password = props.getProperty("password");
Class.forName(driver);
}
public static Connection getConnection() throws SQLException {
Connection con = tl.get();
if (con == null) {
con = DriverManager.getConnection(url, username, password);
tl.set(con);
}
return con;
}
// 關閉連線、Statement、ResultSet 等輔助方法...
}
db_mysql.propertiesdriver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=root
List<Emp> findAllEmp()。getEmpDao() 返回具體實現(此處為 MySQL 版)。PreparedStatement 防注入,配合工具類管理連線。// EmpDaoMySQL 關鍵片段
public List<Emp> findAllEmp() throws Exception {
List<Emp> list = new ArrayList<>();
Connection conn = ConnectionUtils.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_emp");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(new Emp(rs.getInt(1), rs.getString(2), rs.getDouble(3)));
}
ConnectionUtils.closeAll(ps, rs); // 統一釋放資源
return list;
}
掌握 DAO 模式精髓,為後續學習 ORM 框架打下堅實基礎。