BaseDao封裝JavaWeb的增刪改查的實現(xiàn)代碼
什么是BaseDao?
Basedao 是一種基于數(shù)據(jù)訪問對象(Data Access Object)模式的設計方法。它是一個用于處理數(shù)據(jù)庫操作的基礎類,負責封裝數(shù)據(jù)庫訪問的底層操作,提供通用的數(shù)據(jù)庫訪問方法。
Basedao 主要用于簡化數(shù)據(jù)庫操作的代碼開發(fā),并提供一致性和可維護性。它通常包含有對數(shù)據(jù)庫的增加、刪除、修改和查詢等操作方法,以及一些基本的事務處理功能。
Basedao 可以通過繼承來擴展具體的數(shù)據(jù)庫操作方法,使得在具體的業(yè)務實現(xiàn)中可以更加專注于業(yè)務邏輯的實現(xiàn),而不需要關注底層數(shù)據(jù)庫的細節(jié)。
通過使用 Basedao,開發(fā)人員可以更加高效地進行數(shù)據(jù)庫操作的開發(fā),減少了重復的代碼編寫,提高了代碼的可維護性和可讀性。
為什么需要BaseDao?
BaseDao 的優(yōu)點包括:
- 代碼復用(共性抽取):BaseDao 封裝了常見的數(shù)據(jù)庫操作方法,可以被不同的業(yè)務邏輯類多次調(diào)用,避免了重復編寫相同的數(shù)據(jù)庫操作代碼,提高了代碼的復用性。
- 提高開發(fā)效率:BaseDao 提供了高級的數(shù)據(jù)庫操作方法,開發(fā)人員可以直接調(diào)用這些方法,減少了重復的開發(fā)工作,提高了開發(fā)效率。
- 降低代碼耦合度:BaseDao 封裝了底層數(shù)據(jù)庫的細節(jié),通過調(diào)用 BaseDao 的方法,業(yè)務邏輯類可以和具體的數(shù)據(jù)庫實現(xiàn)解耦,減少了業(yè)務邏輯類和數(shù)據(jù)庫之間的直接依賴,提高了代碼的可維護性和可擴展性。
- 提供事務支持:BaseDao 通常會提供事務處理的功能,可以保證數(shù)據(jù)庫操作的一致性。開發(fā)人員可以通過 BaseDao 來處理事務,確保在一次操作中,要么全部成功,要么全部失敗,避免了數(shù)據(jù)不一致的情況。
總的來說,BaseDao 通過封裝數(shù)據(jù)庫操作,提供高級的數(shù)據(jù)庫操作方法,降低代碼耦合度,提供事務支持等優(yōu)點,可以提高開發(fā)效率,簡化數(shù)據(jù)庫操作,提高代碼的可維護性和可擴展性。
BaseDao的實現(xiàn)邏輯
簡單來說BaseDao就是對數(shù)據(jù)庫底層操作業(yè)務進行共性抽取,下面就以學生信息為例~
1、在學生信息管理系統(tǒng)中,不論增刪改查還是特殊業(yè)務都離不開每次訪問數(shù)據(jù)庫的配置驅(qū)動以及獲取連接和關閉連接,所以這兩步是必然封裝的
/** * 獲取數(shù)據(jù)庫連接對象 */ public Connection getConnection() throws Exception { //獲取連接對象方法 //加載配置文件 Properties properties = new Properties(); properties.load(Files.newInputStream(Paths.get("D:\\druid.properties"))); //創(chuàng)建一個指定參數(shù)的數(shù)據(jù)庫連接池 DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); return dataSource.getConnection(); //返回連接對象 }
因為當時博主訪問數(shù)據(jù)庫是采用Druid連接池,所以配置驅(qū)動就使用配置文件的方式,配置文件( .properties )代碼如下:
driverClassName = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/student?useServerPrepStmts=true username = root password = root initialSize = 10 maxActive = 30 maxWait = 1000
關閉連接方法封裝代碼如下:
/** * 關閉數(shù)據(jù)庫連接 * @param conn 數(shù)據(jù)庫連接 * @param stmt PreparedStatement預處理對象 * @param rs 結果集 */ public void closeAll(Connection conn, PreparedStatement stmt, ResultSet rs) { //關閉連接方法 // 若結果集對象(RresuleSet)不為空,則關閉 if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } // 若預處理對象(PreparedStatement)不為空,則關閉 if (stmt != null) { try { stmt.close(); } catch (Exception e) { e.printStackTrace(); } } // 若數(shù)據(jù)庫連接對象(Connection)不為空,則關閉 if (conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
2、通過第一步的調(diào)用能夠返回一個連接對象,那么接下來就可以進行基本的增刪改查操作, 增刪改都屬于對數(shù)據(jù)做更新,所以先做增刪改
/** * 增、刪、改的操作 * @param preparedSql 預編譯的 SQL 語句 * @param param 參數(shù)的字符串數(shù)組 * @return 影響的行數(shù) */ public int updateRow (String preparedSql, Object[] param) throws Exception { //增刪改操作的方法 PreparedStatement preparedStatement = null; //創(chuàng)建預處理對象并初始為空(通過預處理可以防止SQL惡意注入) int row = 0; //初始受影響行數(shù)(當受影響行數(shù)大于0時,說明執(zhí)行成功數(shù)據(jù)則更新) Connection connection = getConnection(); //調(diào)用getConnection()方法獲取數(shù)據(jù)庫連接 try { preparedStatement = connection.prepareStatement(preparedSql); //對sql形參預處理 if (param != null) { //形參數(shù)組(注入?yún)?shù))不為空時,循環(huán)遍歷對預處理sql注入?yún)?shù) for (int i = 0; i < param.length; i++) { //為預編譯sql設置參數(shù) preparedStatement.setObject(i + 1, param[i]); } } row = preparedStatement.executeUpdate(); //執(zhí)行sql語句并得到受影響的行數(shù) closeAll(connection,preparedStatement,null); //調(diào)用closeAll()方法關閉資源,因為執(zhí)行操作不含查詢,則將結果集的實參傳空 } catch (SQLException e) { e.printStackTrace(); } return row; //返回受影響行數(shù) }
因為sql語句中需要的參數(shù)與類型是不確定的,則用Object類型數(shù)組作為容器
3、至此就剩查詢操作了,在封裝前需要創(chuàng)建一個實體類,以至于后續(xù)每個實體類都可以代表為一行數(shù)據(jù),代碼如下:
public class Student { //初始字段 private int id; private String name; private int age; public Student(int id, String name, int age) { //構造函數(shù) this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { //toString方法 return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
實體對象有了,那么走你:
public List<Student> queryData (String sql, Object[] param) throws Exception { //查詢操作的方法 PreparedStatement preparedStatement = null; //創(chuàng)建預處理對象并初始為空(通過預處理可以防止SQL惡意注入) Connection connection = getConnection(); //調(diào)用getConnection()方法獲取數(shù)據(jù)庫連接 preparedStatement = connection.prepareStatement(sql); //調(diào)用getConnection()方法獲取數(shù)據(jù)庫連接 if (param != null) { //形參數(shù)組(注入?yún)?shù))不為空時,循環(huán)遍歷對預處理sql注入?yún)?shù) for (int i = 0; i < param.length; i++) { //為預編譯sql設置參數(shù) preparedStatement.setObject(i + 1, param[i]); } } ResultSet resultSet = preparedStatement.executeQuery(); //得到返回的結果集 List<Student> list = new ArrayList<Student>(); //創(chuàng)建List接口對象,泛型為指定Student對象類型,代表每個實體對象都是一行數(shù)據(jù) while (resultSet.next()) { //循環(huán)遍歷結果集,將每行數(shù)據(jù)封裝成Student對象,并添加到List集合中 Student student= new Student(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3)); //獲取結果集中的數(shù)據(jù)存入Student對象中 list.add(student); //將Student對象存入list接口中 } closeAll(connection,preparedStatement,resultSet); //調(diào)用closeAll()方法關閉數(shù)據(jù)庫連接 return list; //返回List集合對象 }
接下來創(chuàng)建一個測試類進行檢查:
1、增刪改測試
//增刪改測試 BaseDao baseDao = new BaseDao(); //創(chuàng)建BaseDao對象 String sql = "insert into student(id,name,age) values(?,?,?)"; //定義預處理sql Object[] list = {6, "老八", 35}; //將sql需要的參數(shù)存入至Object類型的數(shù)組 int add = baseDao.updateRow(sql, list); //調(diào)用增刪改的方法并接收返回的受影響行數(shù) if (add > 0) { //受影響行數(shù)大于0則說明數(shù)據(jù)更新成功 System.out.println("新增成功!受影響行數(shù):" + add); } /* 刪除、修改也是一樣 */
控制臺:
2、查詢測試
//查詢測試 BaseDao baseDao = new BaseDao(); //創(chuàng)建BaseDao對象 String sql = "select * from student"; //定義預處理sql List<Student> list = baseDao.queryData(sql, null); //創(chuàng)建List接口,泛型為Student對象類型,用于存儲查詢返回的數(shù)據(jù) for (Student student : list) { System.out.println(student.getId() + "\t\t" + student.getName() + "\t\t" + student.getAge()); //輸出數(shù)據(jù) }
控制臺:
這么一來,JavaWeb中的每次增刪改查都可以簡明的實現(xiàn),增刪改查以外的特殊性業(yè)務功能可在BaseDao對象中具體實現(xiàn)方法
以上就是BaseDao封裝JavaWeb的增刪改查的實現(xiàn)代碼的詳細內(nèi)容,更多關于BaseDao封裝JavaWeb的資料請關注腳本之家其它相關文章!