日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JDBC之二:DAO模式

發布時間:2024/1/23 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JDBC之二:DAO模式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

JDBC之二:DAO模式

@(JAVA)[java]

詳細代碼請參見 https://github.com/lujinhong/dao

一、前期準備

1、創建數據庫

create database filter_conf;

2、創建表并插入數據

create table T_CATEGORY(cid Int, title varchar(256), sequnce int, deleted int);insert into T_CATEGORY values(1,lujinhong,1,1);

3、準備pom.xml

我習慣使用maven作包管理,因此在pom.xml中加入以下內容:

<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.36</version> </dependency>

OK,開工寫代碼

二、java創建

1、創建Dao接口。

package com.ljh.jasonnews.server.dao; import java.sql.Connection; public interface Dao { public Connection getConnection() throws DaoException; }

2、創建BaseDao類,實現Dao接口,主要完成數據庫的打開與關閉

package com.ljh.jasonnews.server.dao;import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;public class DaoBase implements Dao {@Overridepublic Connection getConnection() throws DaoException {try {//注冊JDBC驅動程序Class.forName("com.mysql.jdbc.Driver");//打開一個數據庫連接String URL = "jdbc:mysql://1.2.3.4:3306/filter_conf";String USERNAME = "lujinhong";String PASSWORD = "lujinhong";Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);return conn;//return dataSource.getConnection();} catch (Exception e) {e.printStackTrace();throw new DaoException();}}protected void closeDbObject(ResultSet rs, Statement stmt, Connection conn){if(rs != null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if(stmt != null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if(conn != null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}

3、創建DaoException。

package com.ljh.jasonnews.server.dao;public class DaoException extends Exception{private String message;public DaoException(){}public DaoException(String message){this.message = message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public String toString(){return message;}}

以上為jdbc DAO模式的基本步驟,主要用于獲取連接及異常處理。

以下步驟對于每個表均要進行新增類(Dao,***DaoImpl,model.)以及在類中新增方法(DaoFactory)。

4、創建DaoFactory類,用于生產Dao對象。

對于較少的連接,可以在factory中每次直接new 一個***DaoImpl對象,如本例。
對于某些較多的連接,可能需要使用連接池等限制連接數量,說見本文最后面。

package com.ljh.jasonnews.server.dao.factory;import com.ljh.jasonnews.server.dao.CategoryDao; import com.ljh.jasonnews.server.dao.impl.CategoryDaoImpl;public class DaoFactory {public static CategoryDao getCategoryDao() {return new CategoryDaoImpl();} }5、創建Model類。package com.ljh.jasonnews.server.model;public class Category {public int getCid() {return cid;}public void setCid(int cid) {this.cid = cid;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public int getSequnce() {return sequnce;}public void setSequnce(int sequnce) {this.sequnce = sequnce;}public int getDeleted() {return deleted;}public void setDeleted(int deleted) {this.deleted = deleted;}private int cid;private String title;private int sequnce = 0;private int deleted = 0; }

6、創建***Dao接口,繼承Dao接口。

package com.ljh.jasonnews.server.dao;import java.util.List; import com.ljh.jasonnews.server.model.Category;public interface CategoryDao extends Dao{public List getCategoryList() throws DaoException; }

7、創建***DaoImpl類,繼承DaoBase類。

package com.ljh.jasonnews.server.dao.impl;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;import com.ljh.jasonnews.server.dao.CategoryDao; import com.ljh.jasonnews.server.dao.DaoBase; import com.ljh.jasonnews.server.dao.DaoException; import com.ljh.jasonnews.server.model.Category;public class CategoryDaoImpl extends DaoBase implements CategoryDao {@Overridepublic List getCategoryList() throws DaoException{String GET_CATEGORY_SQL = "SELECT * FROM T_CATEGORY";List categoryList = new ArrayList();Connection conn = null;PreparedStatement pStatment =null;ResultSet rs = null;try{conn = getConnection();System.out.println("a");pStatment = conn.prepareStatement(GET_CATEGORY_SQL);System.out.println("b");rs = pStatment.executeQuery();System.out.println("c");while(rs.next()){Category category = new Category();category.setCid(rs.getInt("cid"));category.setTitle(rs.getString("title"));category.setSequnce(rs.getInt("sequnce"));category.setDeleted(rs.getInt("deleted"));categoryList.add(category);}}catch(Exception e){throw new DaoException("Erorr getting Categorys. " + e.getMessage());}finally{closeDbObject(rs, pStatment, conn);} return categoryList;} }

其它說明:

1、創建TestCase,測試數據庫連接。

package com.ljh.jasonnews.server.dao.test;import java.util.Iterator; import java.util.List; import org.junit.Test; import com.ljh.jasonnews.server.dao.CategoryDao; import com.ljh.jasonnews.server.dao.impl.CategoryDaoImpl; import com.ljh.jasonnews.server.model.Category;public class CategoryDaoTest {@Testpublic void test() throws Exception{CategoryDao categoryDao = DaoFactory.getCategoryDao();List categoryList = categoryDao.getCategoryList();Iterator iterator = categoryList.iterator();while(iterator.hasNext()){Category category = iterator.next();System.out.println(category.getCid()+" "+ category.getTitle()+" "+category.getSequnce()+" "+ category.getDeleted()+" ");} } }

2、在數據庫中訪問數據,最重要且最費時的操作經常是建立連接。按規則,設計良好的應用程序數據庫連接應該始終是采用連接池的。

一般而言,使用連接池有以下三種方法:

  • Apache Commons DBCP
  • C3p0
  • Tomcat7中的Tomcat JDBCConnection Pool

    使用Tomcat的項目,建立直接使用TomcatJDBC Connection Pool。調用DataSource.getConnection()方法比較快,因為連接永遠不會被關閉:關閉連接時,只要將連接返回池中即可。但是,JNDI查找比較慢,因此,被返回的DataSource經常會被緩存起來。

注:

(1)在調試中,未能使用連接池完成數據庫連接,因此本示例中未使用連接池,關于連接池,可參考DataSourceCache.java,但關鍵是context.xml與web.xml中的配置。

(2)在需要調用context相關的應用中,不能直接使用junit進行測試,而必須創建一個jsp或者servlet,否則,在以下代碼中會報錯:

Context envContext = (Context)context.lookup("java:/comp/env");

(3)作用連接池有JNDI及依賴注入2種方式,目前更推薦使用依賴注入。

總結

以上是生活随笔為你收集整理的JDBC之二:DAO模式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。