Source code analysis of ORM framework: Introduction: Java JDBC, ormframework

Source: Internet
Author: User
Tags driver manager

Source code analysis of ORM framework: Introduction: Java JDBC, ormframework

If you have found an ORM definition on Baidu Encyclopedia: Object relationship ing (English: Object Relational Mapping, ORM for short, or O/RM, or O/R mapping ), it is a program technology used to convert data of different types of systems in object-oriented programming languages. In effect, it is actually a "Virtual Object Database" that can be used in programming languages ". The ORM Framework is a programming model that provides object-to-database relationship ing. Currently, MyBaits and Hibernate are popular frameworks. At the beginning of this chapter, we will analyze the source code of these two frameworks to better understand what ORM is.

Before analyzing the source code of MyBaits3 and Hibernate4 popular ORM frameworks, let's take a look at JDBC, which is the basis of all these frameworks. Speaking of JDBC, Let's first look at the classes under the java. SQL package.



Let's take a look at the complete process of jdbc data access.

   Connection con = null;   Statement stmt = null;   ResultSet rs = null;   try{       Class.forName("com.mysql.jdbc.Driver");       con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "root", "123456");       stmt = con.createStatement();              String sql = "select * from `table`";       rs = stmt.executeQuery(sql);               ResultSetMetaData rsmd = rs.getMetaData();       int j = 0;       j = rsmd.getColumnCount();       for(int k = 0; k<j; k++){           System.out.print(rsmd.getCatalogName(k+1));           System.out.print("\t");       }       while(rs.next())       {           for(int i=0;i<j;i++)           {               System.out.print(rs.getString(i+1));               System.out.print("\t");           }       }   }   catch(Exception e1)   {       System.out.println(e1.toString());   }   finally{           try       {           if(rs != null) rs.close();           if(stmt != null) stmt.close();           if(con != null) con.close();       }       catch(SQLException e)       {           System.out.println(e.toString());       }               }
Class. forName (String) is used to load classes in java reflection. Here a driver is loaded and DriverManager. getConnection () gets the database connection. Let's take a look at the DriverManager Class.

As the Driver manager, DriverManager has an internal class DriverInfo used to access the Driver information and maintain a Driver object. After the driver is loaded, you need to obtain the database connection from DriverManager.

public static Connection getConnection(String url,        String user, String password) throws SQLException {        java.util.Properties info = new java.util.Properties();        if (user != null) {            info.put("user", user);        }        if (password != null) {            info.put("password", password);        }        return (getConnection(url, info, Reflection.getCallerClass()));    }
Private static Connection getConnection (String url, java. util. Properties info, Class <?> Caller) throws SQLException {/** if callerCl is empty, we have to check the class loader of the application to load rt. JDBC driver other than jar */ClassLoader callerCL = caller! = Null? Caller. getClassLoader (): null; synchronized (DriverManager. class) {// synchronize loading of the correct classloader. if (callerCL = null) {callerCL = Thread. currentThread (). getContextClassLoader () ;}} if (url = null) {throw new SQLException ("The url cannot be null", "08001");} println ("DriverManager. getConnection (\ "" + url + "\") "); SQLException reason = null; for (DriverInfo aDriver: regi SteredDrivers) {// skip if (isDriverAllowed (aDriver. driver, callerCL) {try {println ("trying" + aDriver. driver. getClass (). getName (); // use the driver to try to connect to the database Connection con = aDriver. driver. connect (url, info); if (con! = Null) {println ("getConnection returning" + aDriver. driver. getClass (). getName (); return (con) ;}} catch (SQLException ex) {if (reason = null) {reason = ex ;}} else {println ("skipping: "+ aDriver. getClass (). getName () ;}// omitting some code ...}
DriverManager calls the static code block during class loading to initialize and load the database Driver. When the user uses getConnection, the Driver tries to connect to the database. Once a Driver connects to the current database, the Driver returns the connection. Take Mysql-connector-java as an example. If you want to connect your database to a JDBC database, you must implement the Connection interface. Connection not only provides transaction operations, but also an abstract method createStatement can create an SQL Statement. Here we will talk about the second important class Statement of JDBC. This is also an interface that requires developers of different databases to provide their own implementation. The main function of this object is to execute SQL statements to return ResultSet. Similarly, this ResultSet is also an interface that requires third-party implementation, it is similar to a Table data structure. Each time you call next (), it points to the next database record and calls different getXXX (String columnName) for different types of fields) you can obtain the value of the field corresponding to the record. In addition to these main interfaces, JDBC also provides the DatabaseMetaData interface describing database properties and some Date and exception classes.

From the above analysis, we can see that the jdbc api is actually very simple. It is just a bridge between java and database, and only provides a general specification, all operations on a specific database must be implemented by a third party.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.