编程知识 cdmana.com

The elegant explanation Java operation database way and the design pattern application

1. Use... At the business level JDBC Direct operation database - The most simple , The most direct operation

1) database url,username,password Write dead in code

     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) use Facade and Command Pattern , Use DBUtil Class encapsulation JDBC operation ;
database url,username,password Can be placed in the configuration file ( Such as xml,properties,ini etc. ).
This method is widely used in small programs .

2.DAO(Data Accessor Object) Pattern - The beginning of loose coupling
DAO = data + accessor + domain object

for example User class -domain object (javabean)

UserDAO class -accessor , Methods provided getUser(int id),save(User user) It contains JDBC operation
Use these two types of business logic to complete these operations .

Use Factory Schema can facilitate the migration between different database connections .

3. Database resource management mode

  • 3.1 Database connection pool technology

Resource reuse , Avoid frequent creation , Releasing connections causes a lot of performance overhead ;
Faster system response time ;

By implementing JDBC Part of the resource object interface of ( Connection, Statement, ResultSet ), have access to Decorator Design patterns generate three logical resource objects respectively : PooledConnection, PooledStatement and PooledResultSet.

One of the simplest database connection pool implementation :

public class ConnectionPool {

        private static Vector pools;
        private final int POOL_MAXSIZE = 25;
        /**
         *  Get database connection 
         *  If there are available connections in the current pool , The last one in the pool will be returned ; If there is no , Create a new return 
         */
        public synchronized Connection getConnection() {
               Connection conn = null;
               if (pools == null) {
                      pools = new Vector();
               }
// Join in Java Development and exchange :756584822 Blow water and chat together 

               if (pools.isEmpty()) {
                      conn = createConnection();
               } else {
                      int last_idx = pools.size() - 1;
                      conn = (Connection) pools.get(last_idx);
                      pools.remove(last_idx);
               }

               return conn;
        }

        /**
         *  Put the used database connection back into the pool 
         *  If the connection in the pool has exceeded the threshold , Then close the connection ; Otherwise, put it back in the pool and use it next time 
         */
        public synchronized void releaseConnection(Connection conn) {
               if (pools.size() >= POOL_MAXSIZE)
                      try {
                             conn.close();
                      } catch (SQLException e) {
                             // TODO Automatic generation  catch  block 
                             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 Automatic generation  catch  block 
                      e.printStackTrace();
               } catch (IllegalAccessException e) {
                      // TODO Automatic generation  catch  block 
                      e.printStackTrace();
               } catch (ClassNotFoundException e) {
                      // TODO Automatic generation  catch  block 
                      e.printStackTrace();
               } catch (SQLException e) {
                      // TODO Automatic generation  catch  block 
                      e.printStackTrace();
               }// Join in Java Development and exchange :756584822 Blow water and chat together 

               return conn;
        }
}

Be careful : utilize getConnection() Method derived Connection, Programmers are used to calling conn.close() Method closes the database connection , Then the above database connection mechanism is in vain . Calling conn.close() Method, how to call releaseConnection() Method ? This is the key . here , We use Proxy Patterns and java The reflex mechanism .

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;
      }
     // Join in Java Development and exchange :756584822 Blow water and chat together 

      /**
       *  Bind the dynamic proxy to the specified 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;
      }
     
        /* ( Not  Javadoc)
         * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
         */// Join in Java Development and exchange :756584822 Blow water and chat together 

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               // TODO Automatically generate method stubs 
               Object obj=null;
               if("close".equals(method.getName())){
                      this.pool.releaseConnection(this.conn);
               }
               else{
                      obj=method.invoke(this.conn, args);
               }
              
               return obj;
        }
}

In the actual project , You don't have to design the database connection pooling mechanism from scratch , Now mature open source projects , Such as C3P0,dbcp,Proxool And so on . Generally recommended Apache dbcp, Basic examples of use :

DataSource ds = null;
    try{// Join in Java Development and exchange :756584822 Blow water and chat together 

      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
    Normal precompiled code :
String strSQL=”select name from items where id=?”;
PreparedStatement ps=conn.prepareStatement(strSQL);
ps.setString(1, “2”);
ResultSet rs=ps.executeQuery();
// Join in Java Development and exchange :756584822 Blow water and chat together 

however PreparedStatement It's about specific Connection The associated , once Connection close , It's related PreparedStatement It will also shut down .
In order to create PreparedStatement Buffer pool , Can be in invoke In the method, we use sql Statement to determine if there are any available instances in the pool .

  • Persistence layer design and O/R mapping technology

1) Hernate: Suitable for the development of new products , Make a closed design
Hibernate 2003 By the Jboss To take over , Through the java pojo Object mapping to the database table in , Adopted xml/javareflection Technology, etc. .3.0 Provides a description of stored procedures and handwriting sql Support for , It provides hql Language .
Files needed for development :

hibernate The configuration file : hibernate.cfg.xml  or  hibernate.properties
hibernate  The mapping file : a.hbm.xml
pojo Class source file : a.java  

 Export the relationship between tables :
a.  from java Object to hbm file :xdoclet
b.  from hbm File to java object :hibernate extension
c.  From database to hbm file :middlegen
d.  from hbm File to database :SchemaExport
// Join in Java Development and exchange :756584822 Blow water and chat together 

  • 2)Iatis : It is suitable for transformation of legacy system and reuse of existing database , Very flexible 3) Apache OJB: The advantage lies in full support for standards
    4)EJB: Suitable for clustered servers , Its performance is not as bad as some people criticize 5) JDO (java data object)

Set up a Properties object , To get a JDO Of PersistenceManagerFactory( amount to JDBC Connect... In the pool DataSource), And get a PersistenceManager object ( amount to JDBC Medium Connection object ), after , You can use this PersistenceManager Object to increase 、 to update 、 Delete 、 Query object .
JDOQL yes JDO Query language of ; It's kind of like SQL, But according to Java Grammatical .

  • Based on the open source framework Struts+Spring+Hibernate Implementation scheme

Example : This is a 3 Layer architecture web Program , Through one Action To call the business agent , And then call back through it DAO class . The flow chart below shows MyUsers How it works . The numbers show the sequence of the processes , from web layer (UserAction) To the middle tier (UserManager), To the data layer (UserDAO), Then return .
Spring yes AOP, UserManager and UserDAO It's all interfaces .

  • 1)web layer (UserAction) : Call the interface method of the middle layer , take UserManager Inject as an attribute .
    Use the popular Struts frame , Although many people are dismissive , But this technology is widely used in the industry , Can satisfy the basic function , It can reduce the cost of training and learning .

  • 2) Middle layer (UserManager): take UserDAO Inject as an attribute , Its implementation is mainly to call some methods of data layer interface ; It's in transaction control . use Spring Framework implementations ,IOC And AOP It's a pronoun for it , The function is all ready , A great architecture .

  • 3) The data layer (UserDAO): Implement class inheritance HibernateDaoSupport class , In this class, you can call getHibernateTemplate() To perform specific data operations .

use Hibernate do O/R mapping, There are signs that ,Hibernate Namely EJB3.0 Of beta edition .
 Insert picture description here

版权声明
本文为[osc_ bwwgdzfr]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225132003246Q.html

Scroll to Top