Edzy_Java

            BlogJava :: 首頁 ::  ::  ::  :: 管理 ::
            58 隨筆 :: 12 文章 :: 11 評(píng)論 :: 0 Trackbacks

          1.?? 在業(yè)務(wù)層使用JDBC直接操作數(shù)據(jù)庫-最簡(jiǎn)單,最直接的操作緊耦合方式,黑暗中的痛苦
          ?
          1)數(shù)據(jù)庫url,username,password寫死在代碼中
          ??? Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
          ??? String url="jdbc:oracle:thin:@localhost:1521:orcl";
          ??? String user="scott";
          ??? String password="tiger";
          ??? Connection conn= DriverManager.getConnection(url,user,password);?
          ??? Statement stmt=conn.createStatement(
          ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
          ??? String sql="select * from test";
          ??? ResultSet rs=stmt.executeQuery(sql);
          ?
          2)采用Facade和Command模式,使用DBUtil類封裝JDBC操作;
          ????? 數(shù)據(jù)庫url,username,password可以放在配置文件中(如xml,properties,ini等)。
          ????? 這種方法在小程序中應(yīng)用較多。
          ?
          2.DAO(Data Accessor Object)模式-松耦合的開始

          DAO = data + accessor + domain object
          ?
          例如User類-domain object (javabean)
          ??????? UserDAO類-accessor ,提供的方法getUser(int id),save(User user)內(nèi)包含了JDBC操作
          在業(yè)務(wù)邏輯中使用這兩個(gè)類來完成數(shù)據(jù)操作。
          ?
          ??????? 使用Factory模式可以方便不同數(shù)據(jù)庫連接之間的移植。
          ?
          3.數(shù)據(jù)庫資源管理模式

          3.1 數(shù)據(jù)庫連接池技術(shù)

          資源重用,避免頻繁創(chuàng)建,釋放連接引起大大量性能開銷;
          更快的系統(tǒng)響應(yīng)速度;
          ?
          通過實(shí)現(xiàn)JDBC的部分資源對(duì)象接口( Connection, Statement, ResultSet ),可以使用Decorator設(shè)計(jì)模式分別產(chǎn)生三種邏輯資源對(duì)象: PooledConnection, PooledStatement和 PooledResultSet。
          ?
          ??????? 一個(gè)最簡(jiǎn)單地?cái)?shù)據(jù)庫連接池實(shí)現(xiàn):
          public class ConnectionPool {
          ?
          ?????? private static Vector pools;
          ?????? private final int POOL_MAXSIZE = 25;
          ?????? /**
          ??????? * 獲取數(shù)據(jù)庫連接
          ??????? * 如果當(dāng)前池中有可用連接,則將池中最后一個(gè)返回;若沒有,則創(chuàng)建一個(gè)新的返回
          ??????? */
          ?????? public synchronized Connection getConnection() {
          ????????????? Connection conn = null;
          ????????????? if (pools == null) {
          ???????????????????? pools = new Vector();
          ????????????? }
          ?
          ????????????? if (pools.isEmpty()) {
          ???????????????????? conn = createConnection();
          ????????????? } else {
          ???????????????????? int last_idx = pools.size() - 1;
          ???????????????????? conn = (Connection) pools.get(last_idx);
          ???????????????????? pools.remove(last_idx);
          ????????????? }
          ?
          ????????????? return conn;
          ?????? }
          ?
          ?????? /**
          ??????? * 將使用完畢的數(shù)據(jù)庫連接放回池中
          ??????? * 若池中連接已經(jīng)超過閾值,則關(guān)閉該連接;否則放回池中下次再使用
          ??????? */
          ?????? public synchronized void releaseConnection(Connection conn) {
          ????????????? if (pools.size() >= POOL_MAXSIZE)
          ???????????????????? try {
          ??????????????????????????? conn.close();
          ???????????????????? } catch (SQLException e) {
          ??????????????????????????? // TODO自動(dòng)生成 catch 塊
          ??????????????????????????? e.printStackTrace();
          ???????????????????? } else
          ???????????????????? pools.add(conn);
          ?????? }
          ?
          ?????? public static Connection createConnection() {
          ????????????? Connection conn = null;
          ????????????? try {
          ???????????????????? Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
          ???????????????????? String url = "jdbc:oracle:thin:@localhost:1521:orcl";
          ???????????????????? String user = "scott";
          ???????????????????? String password = "tiger";
          ???????????????????? conn = DriverManager.getConnection(url, user, password);
          ????????????? } catch (InstantiationException e) {
          ???????????????????? // TODO自動(dòng)生成 catch 塊
          ???????????????????? e.printStackTrace();
          ????????????? } catch (IllegalAccessException e) {
          ???????????????????? // TODO自動(dòng)生成 catch 塊
          ???????????????????? e.printStackTrace();
          ????????????? } catch (ClassNotFoundException e) {
          ???????????????????? // TODO自動(dòng)生成 catch 塊
          ???????????????????? e.printStackTrace();
          ????????????? } catch (SQLException e) {
          ???????????????????? // TODO自動(dòng)生成 catch 塊
          ???????????????????? e.printStackTrace();
          ????????????? }
          ????????????? return conn;
          ?????? }
          }
          ?
          ??????? 注意:利用getConnection()方法得到的Connection,程序員很習(xí)慣地調(diào)用conn.close()方法關(guān)閉了數(shù)據(jù)庫連接,那么上述的數(shù)據(jù)庫連接機(jī)制便形同虛設(shè)。?? 在調(diào)用conn.close()方法方法時(shí)如何調(diào)用releaseConnection()方法?這是關(guān)鍵。這里,我們使用Proxy模式和java反射機(jī)制。
          ?
          public synchronized Connection getConnection() {
          ????????????? Connection conn = null;
          ????????????? if (pools == null) {
          ???????????????????? pools = new Vector();
          ????????????? }
          ?
          ????????????? if (pools.isEmpty()) {
          ???????????????????? conn = createConnection();
          ????????????? } else {
          ???????????????????? int last_idx = pools.size() - 1;
          ???????????????????? conn = (Connection) pools.get(last_idx);
          ???????????????????? pools.remove(last_idx);
          ????????????? }
          ???????
          ??????? ConnectionHandler handler=new ConnectionHandler(this);
          ????????????? return handler.bind(con);
          ?????? }
          ?
          public class ConnectionHandler implements InvocationHandler {
          ???? private Connection conn;
          ???? private ConnectionPool pool;
          ????
          ???? public ConnectionHandler(ConnectionPool pool){
          ??????????? this.pool=pool;
          ???? }
          ????
          ???? /**
          ????? * 將動(dòng)態(tài)代理綁定到指定Connection
          ????? * @param conn
          ????? * @return
          ????? */
          ???? public Connection bind(Connection conn){
          ??????????? this.conn=conn;
          Connection proxyConn=(Connection)Proxy.newProxyInstance(
          conn.getClass().getClassLoader(), conn.getClass().getInterfaces(),this);
          ????????? return proxyConn;
          ???? }
          ????
          ?????? /* (非 Javadoc)
          ??????? * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
          ??????? */
          ?????? public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          ????????????? // TODO自動(dòng)生成方法存根
          ????????????? Object obj=null;
          ????????????? if("close".equals(method.getName())){
          ???????????????????? this.pool.releaseConnection(this.conn);
          ????????????? }
          ????????????? else{
          ???????????????????? obj=method.invoke(this.conn, args);
          ????????????? }
          ?????????????
          ????????????? return obj;
          ?????? }
          }
          ?
          ????? 在實(shí)際項(xiàng)目中,并不需要你來從頭開始來設(shè)計(jì)數(shù)據(jù)庫連接池機(jī)制,現(xiàn)在成熟的開源項(xiàng)目,如C3P0,dbcp,Proxool等提供了良好的實(shí)現(xiàn)。一般推薦使用Apache dbcp,基本使用實(shí)例:
          DataSource ds = null;
          ?? try{
          ???? Context initCtx = new InitialContext();
          ???? Context envCtx = (Context) initCtx.lookup("java:comp/env");
          ???? ds = (DataSource)envCtx.lookup("jdbc/myoracle");
          ??????? if(ds!=null){
          ??????????????? out.println("Connection is OK!");
          ??????????????? Connection cn=ds.getConnection();
          ??????????????? if(cn!=null){
          ??????????????????????? out.println("cn is Ok!");
          ??????????????? Statement stmt = cn.createStatement();
          ???????????????? ResultSet rst = stmt.executeQuery("select * from BOOK");
          ??????????????? out.println("<p>rst is Ok!" + rst.next());
          ??????????????? while(rst.next()){
          ??????????????????????? out.println("<P>BOOK_CODE:" + rst.getString(1));
          ????????????????? }
          ??????????????????????? cn.close();
          ??????????????? }else{
          ??????????????????????? out.println("rst Fail!");
          ??????????????? }
          ??????? }
          ??????? else
          ??????????????? out.println("Fail!");
          ?????????? }catch(Exception ne){ out.println(ne);
          ???????? }

          3.2 Statement Pool

          ??????? 普通預(yù)編譯代碼:
          String strSQL=”select name from items where id=?”;
          PreparedStatement ps=conn.prepareStatement(strSQL);
          ps.setString(1, “2”);
          ResultSet rs=ps.executeQuery();
          ?
          ??????? 但是PreparedStatement 是與特定的Connection關(guān)聯(lián)的,一旦Connection關(guān)閉,則相關(guān)的PreparedStatement 也會(huì)關(guān)閉。
          ??????? 為了創(chuàng)建PreparedStatement 緩沖池,可以在invoke方法中通過sql語句判斷池中還有沒有可用實(shí)例。
          ?
          4. 持久層設(shè)計(jì)與O/R mapping 技術(shù)

          1)Hernate:適合對(duì)新產(chǎn)品的開發(fā),進(jìn)行封閉化的設(shè)計(jì)
          Hibernate 2003年被Jboss接管,通過把java pojo對(duì)象映射到數(shù)據(jù)庫的table中,采用了xml/javareflection技術(shù)等。3.0提供了對(duì)存儲(chǔ)過程和手寫sql的支持,本身提供了hql語言。
          ??????? 開發(fā)所需要的文件:
          hibernate配置文件: hibernate.cfg.xml 或 hibernate.properties
          hibernate 映射文件: a.hbm.xml
          pojo類源文件: a.java  
          ?
          ??????? 導(dǎo)出表與表之間的關(guān)系:
          a. 從java對(duì)象到hbm文件:xdoclet
          b. 從hbm文件到j(luò)ava對(duì)象:hibernate extension
          c. 從數(shù)據(jù)庫到hbm文件:middlegen
          d. 從hbm文件到數(shù)據(jù)庫:SchemaExport
          ?
          2)Iatis :適合對(duì)遺留系統(tǒng)的改造和對(duì)既有數(shù)據(jù)庫的復(fù)用,有很強(qiáng)的靈活性
          3)Apache OJB:優(yōu)勢(shì)在于對(duì)標(biāo)準(zhǔn)的全面支持
          4)EJB:適合集群服務(wù)器,其性能也不象某些人所詬病的那么差勁
          5)JDO (java data object)
          ??????? 設(shè)置一個(gè)Properties對(duì)象,從而獲取一個(gè)JDO的PersistenceManagerFactory(相當(dāng)于JDBC連接池中的DataSource),進(jìn)而獲得一個(gè)PersistenceManager對(duì)象(相當(dāng)于JDBC中的Connection對(duì)象),之后,你可以用這個(gè)PersistenceManager對(duì)象來增加、更新、刪除、查詢對(duì)象。
          ??????? JDOQL是JDO的查詢語言;它有點(diǎn)象SQL,但卻是依照J(rèn)ava的語法的。
          ?
          5. 基于開源框架的Struts+Spring+Hibernate實(shí)現(xiàn)方案

          ??????? 示例:這是一個(gè)3層架構(gòu)的web 程序,通過一個(gè)Action 來調(diào)用業(yè)務(wù)代理,再通過它來回調(diào) DAO類。下面的流程圖表示了MyUsers是如何工作的。數(shù)字表明了流程的先后順序,從web層(UserAction)到中間層(UserManager),再到數(shù)據(jù)層(UserDAO),然后返回。
          Spring是AOP, UserManager和UserDAO都是接口.
          1)?web層(UserAction) :調(diào)用中間層的接口方法,將UserManager作為屬性注入。
          ??????? 采用流行的Struts框架,雖然有很多人不屑一顧,但是這項(xiàng)技術(shù)在業(yè)界用的比較普遍,能滿足基本的功能,可以減少培訓(xùn)學(xué)習(xí)成本。
          2)?中間層(UserManager):將UserDAO作為屬性注入,其實(shí)現(xiàn)主要是調(diào)用數(shù)據(jù)層接口的一些方法;它處于事務(wù)控制中。
          ??????? 采用Spring框架實(shí)現(xiàn),IOC與AOP是它的代名詞,功能齊全,非常棒的一個(gè)架構(gòu)。
          3)?數(shù)據(jù)層(UserDAO):實(shí)現(xiàn)類繼承HibernateDaoSupport類,在該類中可以調(diào)用getHibernateTemplate()的一些方法執(zhí)行具體的數(shù)據(jù)操作。
          ??????? 采用Hibernate做O/R mapping,從種種跡象可以看出,Hibernate就是EJB3.0的beta版。

          posted on 2006-11-15 18:16 lbfeng 閱讀(275) 評(píng)論(0)  編輯  收藏 所屬分類: 數(shù)據(jù)庫技術(shù)雜談

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 通州区| 光泽县| 惠水县| 建湖县| 南岸区| 抚顺县| 武乡县| 偃师市| 云龙县| 凉山| 朝阳市| 手机| 绥芬河市| 永德县| 葵青区| 耒阳市| 三门峡市| 尼玛县| 安乡县| 句容市| 大关县| 锦屏县| 泰和县| 台中市| 鹿邑县| 安徽省| 雅江县| 正镶白旗| 榆林市| 平阴县| 平果县| 新竹县| 沁水县| 云和县| 桐庐县| 明水县| 岢岚县| 阳高县| 栾城县| 绥德县| 中山市|