Java SE 6 new features: Java DB and JDBC 4.0

Source: Internet
Author: User
Tags connection pooling throwable java se

Http://www.ibm.com/developerworks/cn/java/j-lo-jse65/index.html

For a long time, because a large number (and even almost all) of Java applications rely on databases, how to access the database efficiently, reliably, and concisely using the Java language has been a topic that programmers relish. The newly released Java SE 6 is also on the upper floor, providing programmers with many new and useful features. The most notable of these is that Java SE 6 has an embedded 100% database system written in the Java language. Also, Java 6 begins to support a range of new features and properties for JDBC 4.0. In this way, Java SE is more user-friendly and powerful in accessing persistent data.

Databases in Java Db:java 6

Newly installed JDK 6 will probably find that in addition to the traditional bin, JRE and other directories, JDK 6 has a new directory named DB. This is the new member of Java 6: Java DB. This is a pure Java implementation, open source database management system (DBMS), originating from the Apache Software Foundation (ASF) name of the project Derby. It's only 2MB in size, and it's pocket-sized for a database of G. This does not prevent the Derby from being fully functional and supports the features required for almost any database application. Even more commendable is that, based on ASF's strong community power, Derby has the support of large companies including IBM and Sun, as well as the world's best programmers. It is no wonder that Sun will choose its 10.2.2 version to be included in JDK 6 as an embedded database. It's like injecting a new level of vitality into the JDK: Java programmers no longer need to spend a lot of time installing and configuring databases, making it safe, easy to use, standard, and free of database programming. In this chapter, we'll look at the world of Java DB to explore how to use it to write a feature-rich program.

Hello, Java DB: inline-mode Derby

Now that you have the embedded (embedded) database, let's start with a simple example (the code is listed in Listing 1) and try to use it. This program does what most database applications might do: Create a database named Hellodb in the DBMS, create a data table named Hellotable, insert two data into the table, and then query the data and print the results on the console; Delete the tables and databases and release the resources.

Listing 1. HELLOJAVADB's Code
public class Hellojavadb {public static void main (string[] args) {try {//load the driver Class.fo            Rname ("Org.apache.derby.jdbc.EmbeddedDriver"). newinstance ();            System.out.println ("Load the embedded Driver");            Connection conn = null;            Properties Props = new properties ();  Props.put ("User", "user1");           Props.put ("Password", "user1"); Create and connect the database named Hellodb conn=drivermanager.getconnection ("Jdbc:derby:hellodb;create=tr            UE ", props);            System.out.println ("Create and connect to Hellodb");            Conn.setautocommit (FALSE);            Create a table and insert records Statement s = conn.createstatement ();            S.execute ("CREATE table hellotable (name varchar (), score int)");            SYSTEM.OUT.PRINTLN ("Created table hellotable");            S.execute ("INSERT into hellotable values (' Ruth Cao ', 86)"); S.execute ("INSERT INTO hellotable VALues (' Flora Shi ', 92) ");  List the records ResultSet rs = s.executequery ("Select name, score from Hellotable ORDER            by score ");            System.out.println ("Name\t\tscore");                while (Rs.next ()) {StringBuilder builder = new StringBuilder (rs.getstring (1));                Builder.append ("\ t");                Builder.append (Rs.getint (2));            System.out.println (Builder.tostring ());            }//delete the table S.execute ("drop table hellotable");                        SYSTEM.OUT.PRINTLN ("Dropped table hellotable");            Rs.close ();            S.close ();            System.out.println ("Closed result set and statement");            Conn.commit ();            Conn.close ();                        System.out.println ("Committed transaction and closed connection");      try {//Perform a clean Shutdown drivermanager.getconnection ("jdbc:derby:;shutdown=true");      } catch (SQLException se) {System.out.println ("Database shut down normally"); }} catch (Throwable e) {//Handle the exception} System.out.println ("Simpleapp finished    "); }}

Next, we type the following command on the command line (in this case, the Windows platform, and, of course, some changes under other systems):

Listing 2. Run the HELLOJAVADB command
JAVA–CP.; %java_home%\db\lib\derby.jar hellojavadb

The program will execute as we expect, and Figure 1 is part of the execution result screenshot:

Figure 1. HELLOJAVADB execution results of the program

The above procedure is no different from the past. The difference is that we don't need to bother with the configuration of the DBMS because Derby has automatically created a new directory named Hellodb in the current directory to physically store the data and logs. All you need to do is pay attention to the naming problem: The driver name should be in inline mode org.apache.derby.jdbc.EmbeddedDriver ; A new database needs to be added after the protocol is created create=true . In addition, closing all databases and Derby engines can use the following code:

Listing 3. Close all databases and Derby engines
Drivermanager.getconnection ("Jdbc:derby:;shutdown=true");

If you want to close only one database, you can call:

Listing 4. Close a database
Drivermanager.getconnection ("Jdbc:derby:hellodb;shutdown=true");

In this way, Derby, which uses embedded mode, maintains and manages the database at a cost close to 0. This is good news for people who want to concentrate on writing code. However, one cannot help but ask: since there is an embedded pattern, why does most DBMS not take such a pattern? Try a little experiment. When we run the HELLOJAVADB program in two command-line windows at the same time. As a result, the result is the same as it was, and the other error occurred, as shown in Figure 2.

Figure 2. Limitations of inline mode

The reason for the error is simple: When using inline mode, Derby itself does not run in a separate process, but with the application in the same Java virtual machine (JVM). As a result, Derby becomes part of the application just like any other jar file used by the application. It is not difficult to understand why the jar file of Derby was added to the Classpath and our sample program would be able to run smoothly. This also shows that only one JVM can start the database: While two of applications running on different JVM instances will naturally not be able to access the same database.

Given the limitations described above, and the need for multiple connections from different JVMs to access a database, the next section describes another mode of Derby: network server.

Network server Mode

As mentioned above, the network server mode is a more traditional client/server model. We need to start a Derby network server to handle requests from clients, whether they are from the same JVM instance or from another machine on the network. At the same time, the client connects to the server side using the DRDA (distributed relational Database Architecture) protocol. This is a database interaction standard advocated by the Open Group. Figure 3 illustrates the approximate structure of the pattern.

Because of the efforts of the developers of Derby to make the difference between the Web server pattern and the embedded mode smaller, we can do it simply by modifying the program in Listing 1. As shown in Listing 5, we have added a new function and some string variables to the hellojavadb. It is not difficult to see that the new code only changes some of the strings specifically mentioned in the previous section: The Driver class is org.apache.derby.jdbc.ClientDriver , and the protocol that connects the database becomes jdbc:derby://localhost:1527/ . This is a URL-like string, and in fact, the connection format for the client of the Derby network is: jdbc:derby://server[:port]/databaseName[;attributeKey=value] . In this example, we use the simplest local machine as the server, while the port is the default 1527 port of Derby.

Figure 3. Derby Network Server Mode schema

Listing 5. HELLOJAVADB in network server mode
public class Hellojavadb {public    static String driver = "Org.apache.derby.jdbc.EmbeddedDriver";    public static String protocol = "Jdbc:derby:";    public static void Main (string[] args) {        //same as before    }    private static void Parsearguments (string[] args) {        if (args.length = = 0 | | args.length > 1) {            return;        }        if (Args[0].equalsignorecase ("Derbyclient")) {            framework = "derbyclient";            Driver = "Org.apache.derby.jdbc.ClientDriver";            protocol = "jdbc:derby://localhost:1527/";}}    }

Of course, just having a client is not enough, we also need to start a network server. The class that controls the network server in Derby is org.apache.derby.drda.NetworkServerControl , so type the following command. If you want to know more about Networkservercontrol, start you can see the help information by simply removing the parameters. The implementation of the Web server side is included in the Derbynet.jar by Derby.

Listing 6. Start a network server
JAVA-CP.; " C:\Program Files\java\jdk1.6.0\db\lib\derby.jar ";" C:\Program Files\java\jdk1.6.0\db\lib\derbynet.jar "Org.apache.derby.drda.NetworkServerControl start

Correspondingly, the implementation of the network client is included in the Derbyclient.jar. So, simply add the jar file to the Classpath and the modified client will be able to read the data successfully. Once again, try using two command-line windows to connect to the database to get the right results. If you no longer need the server, you can use the Networkservercontrol shutdown parameter to shut down the server.

More

At this point, the article describes the new members in Java SE 6: Java db (Derby), as well as how to use Java DB in nested mode and in network server mode. Of course, this is just a scratch, and more advanced options need to be found in the documentation for Sun and Derby. At the end of this chapter, we will briefly introduce a few Java DB gadgets to speed up development. They are all located in the Org.apache.derby.tools package and need to be used for information or testing during the development process.

    • ij: A tool for running SQL scripts;
    • Dblook: Schema Extraction (schema extraction) for Derby database, a tool for generating DDL;
    • SysInfo: A tool class for displaying the system and Derby information;

Back to top of page

JDBC 4.0: New features, new APIs

If the previous chapter describes a new member of Java 6, it would have existed, but it was not added to the JDK. In this chapter, we will focus on what new features and new APIs are added to JDBC 4.0.

Auto Load Driver

Before JDBC 4.0, the following is a somewhat ugly code to write the JDBC program:

Listing 7. Registering the JDBC driver
Class.forName ("Org.apache.derby.jdbc.EmbeddedDriver"). newinstance ();

Java.sql.DriverManagerThe internal implementation mechanism determines the appearance of such code. Only by Class.forName locating a specific driver's class file DriverManager.getConnection will the method be able to successfully access the Java application and database. This code adds an unnecessary burden to the programmer, and the JDK developer is aware of that. Starting with Java 6, the application no longer needs to load the driver explicitly, and DriverManager started to be able to assume the task automatically. As a test, we can remove the relevant code from Listing 1 and run it under JRE 6.0 after recompilation, as the original program did.

Curious readers may ask, why is drivermanager able to do automatic loading? This is due to a new mechanism called Service Provider. Programmers familiar with Java security programming may have become commonplace, and it now appears in the JDBC module. The JDBC 4.0 specification stipulates that all JDBC 4.0 driver jar files must contain one java.sql.Driver , which is located in the Meta-inf/services directory of the jar file. Each line in this file describes a corresponding driver class. In fact, the way you write this file is similar to writing a properties file that has only the keyword (key) and no value. Similarly, the text after ' # ' is considered to be a comment. With this description, DriverManager can be found in the current driver file in CLASSPATH, which classes should be loaded. And if we don't have any JDBC 4.0 driver files in CLASSPATH, calling the code in Listing 8 will output an object of the sun.jdbc.odbc.JdbcOdbcDriver type. And a closer look at the directory of JDK 6, this type is described in the %JAVA_HOME%/jre/lib/resources.jar file under the Meta-inf/services directory java.sql.Driver . In other words, this is the default driver in the JDK. And if the developers want to make their driver can be drivermanager found, just need to add the corresponding jar file to CLASSPATH. Of course, we can only explicitly load the driver files that were before JDBC 4.0.

Listing 8. Lists the JDBC drivers on the local machine
enumeration<driver> drivers = drivermanager.getdrivers (); while (Drivers.hasmoreelements ()) {    System.out.println (Drivers.nextelement ());}
RowId

People familiar with large DBMS such as DB2 and Oracle must not be unfamiliar with the concept of ROWID: It is a "hidden" column in a data table, a unique identifier for each row, indicating the physical or logical location of the line. Due to the widespread use of the ROWID type, the new data type in Java SE 6 java.sql.RowId allows the JDBC program to access the ROWID type in SQL. Admittedly, not all DBMS support the ROWID type. Even with support, different ROWID have different life cycles. Therefore, it is DatabaseMetaData.getRowIdLifetime a good practical experience to use to judge the life cycle of a type. We can understand the support of the ROWID type by adding the following code after the program in Listing 1 has been connected.

Listing 9. Learn about support for ROWID types
DatabaseMetaData meta = conn.getmetadata (); System.out.println (Meta.getrowidlifetime ());

The API specification for Java SE 6 java.sql.RowIdLifetime specifies 5 different lifecycles: ROWID_UNSUPPORTED ,, ROWID_VALID_FOREVER ROWID_VALID_OTHER ,, ROWID_VALID_SESSION and ROWID_VALID_TRANSACTION . It is not literally difficult to understand that they show no support for ROWID, ROWID is always effective, and so on. Specific information, you can also refer to the relevant JavaDoc. Readers can try to connect to Derby to experiment and find that the result is ROWID_UNSUPPORTED that Derby does not support ROWID.

Now that the new data types are available, some of the new APIs that fetch and update the contents of the data table are added in Java 6. As with other existing types, ResultSet after getting or CallableStatement following, call the Get/set/update method to get/set/update the RowId object, the sample code is shown in Listing 10.

Listing 10. Get/Set RowId object
Initialize a preparedstatementpreparedstatement pstmt = connection.preparestatement (    "Select rowID, Name, score From hellotable WHERE rowid =? "); /Bind ROWID into prepared statement. Pstmt.setrowid (1, ROWID);//Execute the Statementresultset RSet = Pstmt.executequery (); List the Recordswhile (Rs.next ()) {RowId id = rs.getrowid (1);//Get the immutable RowId object String name = Rs.getstr ING (2);  int score = Rs.getint (3);}

Given the different implementations of different DBMS, RowID objects are usually not portable between different data sources (datasource). Therefore, the API specification for JDBC 4.0 does not recommend removing a RowID object from connection A and using it in connection B to avoid the difficult-to-interpret errors caused by different system differences. As with the DBMS that does not support RowId like Derby, the program will be thrown directly at the Setrowid method SQLFeatureNotSupportedException .

SQLXML

The SQL:2003 Standard introduces Sql/xml as an extension of the SQL standard. Sql/xml defines how the SQL language interacts with XML: How to create XML data, how to embed an XQuery expression in an SQL statement, and so on. As part of JDBC 4.0, the type added by Java 6 java.sql.SQLXML . This type can be used by a JDBC application to initialize, read, and store XML data. java.sql.Connection.createSQLXMLmethod, you can create a blank SQLXML object. Once this object is obtained, it is possible setString setBinaryStream setCharacterStream to initialize the XML data represented by,,, or setResult so on. As an setCharacterStream example, listing 11 shows how an SQLXML object gets an java.io.Writer object and reads the contents line by row from an external XML file to complete the initialization.

Listing 11. Using the Setcharacterstream method to initialize the SQLXML object
SQLXML XML = Con.createsqlxml (); Writer writer = Xml.setcharacterstream (); BufferedReader reader = new BufferedReader (New FileReader ("Test.xml")); String line= null;while (line = Reader.readline ()! = null) {      writer.write (line);}

Because the SQLXML object has the potential to be associated with various external resources and holds these resources in a single transaction. To prevent applications from exhausting resources, Java 6 provides the free method to release its resources. Similar designs appear in java.sql.Array and out Clob .

As for how to use SQLXML to interact with a database, the method is very similar to other types. You can refer to the example in the RowId section in the Java SE 6 API specification to find the corresponding Get/set/update method in SQLXML to build a similar program, which is not described here.

Enhancement of the Sqlexcpetion

Prior to Java SE 6, there were no more than 10 exception types for JDBC. This does not seem to be enough to describe an increasingly complex database exception condition. As a result, designers of Java SE 6 java.sql.SQLException have made significant improvements to the exception system that is rooted. First, SQLException implements the Iterable<Throwable> interface. Listing 12 implements the exception handling mechanism for the listing 1 program. This succinctly iterates through each SQLException and its underlying causes (cause).

Listing 12. SQLException's For-each Loop
Java 6 Codecatch (Throwable e) {   if (e instanceof SQLException) {for       (Throwable ex: (SQLException) e) {            Sys Tem.err.println (Ex.tostring ());}}}    

In addition, Figure 4 shows the entire SQLException anomaly system. In addition to the original subclass of SQLException, the new Exception class in Java 6 is divided into 3 types: SQLReoverableException , SQLNonTransientException , SQLTransientException . SQLNonTransientException SQLTransientException There are several subcategories under and below that detail the various error conditions that may occur in the JDBC program. Most subclasses have a corresponding standard SQLState value, which is a good way to combine the SQL standard with the Java 6 class library.

Figure 4. SQLException Anomaly System

Among the many exception classes, it is more common to SQLFeatureNotSupportedException indicate that the JDBC driver does not support a particular JDBC feature. For example, running the program in Listing 10 under Derby, you can see that the Derby driver does not support the RowId feature. It is also worth mentioning that the SQLClientInfoException direct inheritance from SQLException indicates that when some clients ' properties cannot be set on a database connection, the exception that occurs.

Back to top of page

Summary: More new features and perspectives

In this article, we have introduced some of the most important new features of JDBC in Java SE 6: They include Java DB (Derby) embedded in the JDK and part of JDBC 4.0. Of course, there are many new features that are not covered in this article. For example, it adds support for SQL language NCHAR , NVARCHAR , LONGNVARCHAR and type, and NCLOB Statement provides more flexible and convenient methods for managing objects in the context of database connection pooling.

In addition, the features of Annotation Query were included in the beta version of Java SE 6. This feature defines a series of query and dataset interfaces that programmers can use to compose some Annotation to customize the query and get customized data set results. However, due to the fact that the reference implementation of this feature did not ultimately meet the quality requirements of the JDK, Sun company reluctantly canceled its plan to release it in Java SE 6. We have reason to believe that this feature, along with more new features, will be included in future JDK releases, and applications that build databases using the Java language will become more natural and smoother.

Java SE 6 new features: Java DB and JDBC 4.0

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.