轉載自https://www.runoob.com/note/27029
DAO 模式
DAO (DataAccessobjects 數據存取對象)是指位於業務邏輯和持久化數據之間實現對持久化數據的訪問。通俗來講,就是將數據庫操作都封裝起來。
對外提供相應的接口
在面向對象設計過程中,有一些"套路”用於解決特定問題稱為模式。
DAO 模式提供了訪問關系型數據庫系統所需操作的接口,將數據訪問和業務邏輯分離對上層提供面向對象的數據訪問接口。
從以上 DAO 模式使用可以看出,DAO 模式的優勢就在於它實現了兩次隔離。
- 1、隔離了數據訪問代碼和業務邏輯代碼。業務邏輯代碼直接調用DAO方法即可,完全感覺不到數據庫表的存在。分工明確,數據訪問層代碼變化不影響業務邏輯代碼,這符合單一職能原則,降低了藕合性,提高了可復用性。
- 2、隔離了不同數據庫實現。采用面向接口編程,如果底層數據庫變化,如由 MySQL 變成 Oracle 只要增加 DAO 接口的新實現類即可,原有 MySQ 實現不用修改。這符合 "開-閉" 原則。該原則降低了代碼的藕合性,提高了代碼擴展性和系統的可移植性。
一個典型的DAO 模式主要由以下幾部分組成。
- 1、DAO接口: 把對數據庫的所有操作定義成抽象方法,可以提供多種實現。
- 2、DAO 實現類: 針對不同數據庫給出DAO接口定義方法的具體實現。
- 3、實體類:用於存放與傳輸對象數據。
- 4、數據庫連接和關閉工具類: 避免了數據庫連接和關閉代碼的重復使用,方便修改。
DAO 接口:
public interface PetDao { /** * 查詢所有寵物 */ List<Pet> findAllPets() throws Exception; }
DAO 實現類:
public class PetDaoImpl extends BaseDao implements PetDao { /** * 查詢所有寵物 */ public List<Pet> findAllPets() throws Exception { Connection conn=BaseDao.getConnection(); String sql="select * from pet"; PreparedStatement stmt= conn.prepareStatement(sql); ResultSet rs= stmt.executeQuery(); List<Pet> petList=new ArrayList<Pet>(); while(rs.next()) { Pet pet=new Pet( rs.getInt("id"), rs.getInt("owner_id"), rs.getInt("store_id"), rs.getString("name"), rs.getString("type_name"), rs.getInt("health"), rs.getInt("love"), rs.getDate("birthday") ); petList.add(pet); } BaseDao.closeAll(conn, stmt, rs); return petList; } }
寵物實體類(里面get/set方法就不列出了)
public class Pet { private Integer id; private Integer ownerId; //主人ID private Integer storeId; //商店ID private String name; //姓名 private String typeName; //類型 private int health; //健康值 private int love; //愛心值 private Date birthday; //生日 }
連接數據庫
public class BaseDao { private static String driver="com.mysql.jdbc.Driver"; private static String url="jdbc:mysql://127.0.0.1:3306/epet"; private static String user="root"; private static String password="root"; static { try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } public static void closeAll(Connection conn,Statement stmt,ResultSet rs) throws SQLException { if(rs!=null) { rs.close(); } if(stmt!=null) { stmt.close(); } if(conn!=null) { conn.close(); } } public int executeSQL(String preparedSql, Object[] param) throws ClassNotFoundException { Connection conn = null; PreparedStatement pstmt = null; /* 處理SQL,執行SQL */ try { conn = getConnection(); // 得到數據庫連接 pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement對象 if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setObject(i + 1, param[i]); // 為預編譯sql設置參數 } } ResultSet num = pstmt.executeQuery(); // 執行SQL語句 } catch (SQLException e) { e.printStackTrace(); // 處理SQLException異常 } finally { try { BaseDao.closeAll(conn, pstmt, null); } catch (SQLException e) { e.printStackTrace(); } } return 0; } }