Data management and data persistence in J2EE applications

xiaoxiao2021-03-06  107

This paper analyzes two data management strategies available on the Java platform: Java object serialization and Java Database Connections (JDBC). Although these two data management strategies do not exist, there is no problem, and when managing the enterprise information system, JDBC is easily awesome. In this article, Java Developers G.v.Brahmanyam and Shankar Itchapurapu are introduced to serialization and JDBC and show you the best choice by discussions and instances.

When you are building a corporate information system, you need to ensure that enterprise data is stored, retrieved and displayed in some effective way. For all business, data is unique and largest assets. All software systems involve data, so the importance of data is not too much in any case.

The data management feature of the application consists of four basic operations, and it is often necessary to perform these four operations to enterprise data, which are: establish, retrieve, update, and delete (ie crud). Managing data in the enterprise system involves a long period of time, consistent, successfully executed CRUD operation without having to change the code actually executing these operations. In other words, management data means developing robust, scalable and maintainable software systems to ensure successful CRUD operations, can perform operation in a consistent manner in the life of the software.

This article discusses two available data management strategies in J2EE: Java object serialization and Java database connection (JDBC). We will view the advantages and disadvantages of these two methods. These two data management strategies are essentially excellent. In a particular implementation, the availability of policies depends on the scope of the project (the activity range of activity in the system environment), the system's context (a collection of values ​​at the drive system / subsystem), and other external factors. However, Java serialization is not suitable for enterprise systems, and its data requires organizations that define a good structure (such as RDBMS). We first browse Java object serialization, then view some of the JDBC more important, so that the latter is a key feature that the lack of the former is.

This article does not intend to fully introduce Java object serialization or JDBC. For more information on these two technologies, please review the reference information section.

Java object serialized object serialization is the easiest Java persistence policy. Object Serialization is a process of flattening the object map to a linear sequence of one byte. The object map is some of the relationships that are achieved as the results of the object inheritance, association, and aggregation. The non-transitory instance attribute of the object is written to a persistent storage in the form of bytes. The value of the instance attribute is the value in the memory during execution time serialization. If a Java object is serialized, it must at least implement the java.io.Serializable interface, which has the structure shown below:

Package java.io;

Public Interface Serializable

{}

You can see that the java.io.serializable interface does not declare any way. It is a marker or tag interface. It tells the Java runtime environment, which is sequential. Listing 1 displays an example class that implements the interface.

Listing 1. MySerializableObject.java

Import java.io.serializable;

Public Class MySerializableObject Extends MySuperclass IMPLEments Serializable

{

PRIVATE STRING PROPERTY1 = NULL;

PRIVATE STRING PROPERTY2 = NULL;

Public string getproperty1 () {

Return Property1;

}

Public void setProperty11 (String Val)

{

Property1 = VAL;

}

Public String getProperty2 ()

{

Return Property2;

}

Public void setProperty2 (String Val)

{

Property2 = VAL;

}

Private void writeObject (ObjectOutputStream out)

Throws oException

{

Out.writeObject (getProperty1 ());

Out.writeObject (getProperty2 ());

}

Private Void ReadObject (ObjectInputStream in)

THROWS IOEXCEPTION, ClassNotFoundException

{

SetProperty1 (String) In.readObject ());

SetProperty2 (String) In.readObject ());

}

}

No need to implement the WriteObject (...) and ReadObject (...) method to perform serialization; the Java runtime environment has the default implementation that makes these methods available. However, you can rewrite these methods to provide your own implementation of how to store object status.

With regard to serialization, you need to remember some points. First, during serialization, the entire object map (ie, all parent classes, and reference classes) will be serialized. Second, all instance variables of the Serializable class should be serialized unless they have specified them as temporary, or they have rewritten WriteObject (...) and readObject (...) only serialize those sequences. Instance variables. If it violates the latter rule, an exception will appear at runtime.

Each subsequent J2SE version increases a small amount of an object serialization system. J2SE 1.4 also adds the WriteunShared () method to ObjectOutputStream and ObjectInputStream and objectInputStream. Typically, a serialized flow only includes a serialization example of any given object, and sharing other objects referenced to the object can be retrieved. Usually desire to serialize an object independent of any reference that may maintain other objects. Non-shared read and write methods allow objects to be serialized as new, unique objects, thereby obtaining a less effective effect similar to object clones overhead.

Problem sequences in Java object serialization involves embarking object maps from memory into persistent storage (eg hard drives). This involves a large number of I / O overhead. Usually, serialization is not the best choice for applications:

Manage the storage data of tens of thousands of megabytes frequently update sequential objects

For storage enterprise data, serialization is an error selection because:

The serialized byte stream is only readable for the Java language. This is a major defect because the enterprise system is usually heterogeneous, and many applications should work together with other applications. Object retrieval involves a lot of I / O overhead. No inquiry language used to retrieve data from the serialized object map. Serialization has no built-in security mechanism. Serialization itself does not provide any transaction control mechanism, so it cannot be used in applications that need to be concurrently accessible without using an auxiliary API.

Java Database Connection (JDBC) Java Database Connection (JDBC) is a standard API that interacts with the database using the Java programming language. The call-level interface such as JDBC is a programming interface that allows you to access the SQL command from the outside to process and update data in the database. By providing library routines connected to database routines, they allow SQL calls to integrate into a generic programming environment. In particular, JDBC has a rich collection of an interface that makes an interface extremely simple and intuitive. In the following sections, we will view some of the steps involved through JDBC and database connections. We will pay special attention to how JDBC becomes a corporate data management strategy compared to Java object sequence.

Creating a database connection Before using JDBC to do anything else, you need to get the database driver from the driver vendor and add the library to the classpath. Once this work is finished, you can use the code similar to the following as shown in the Java program to implement the actual connection.

Class.Forname ();

Java.sql.connection conn = drivermanager.getConnection ();

Java object serialization does not require this step because it does not require DBMS using serialization to perform a persistence operation. Serialization is a file-based mechanism; therefore, it is necessary to open an I / O stream in the target file system before serializing an object.

Creating JDBC Statement and PreparedStatement You can send SQL statements to the Database Management System (DBMS) with JDBC Statement objects and should not be confused with SQL statements. The JDBC Statement object is associated with the open connection instead of any individual SQL statement is associated. The JDBC Statement object can be regarded as a channel located on the connection, transmit one or more (your request) SQL statement to DBMS.

In order to create a statement object, you need a connection connection. Complete this work by using the CONNECTION object CON - below the CONNECTION object created.

Statement Stmt = con.createstatement ();

So far, we already have a statement object, but there is no object to the SQL statement of DBMS.

When the database receives the statement, the database engine first analyzes the statement and finds an incorrect error. Once the analysis of the statement is completed, the database must calculate the most effective way to perform it. This may be very expensive on the calculation. Database will check which indexes can provide help, if there is such an index, or check all the rows in the table should be fully read. The database is specimal for data to find the best implementation. Once the query plan is created, the database engine can execute it.

Generating such a plan will take up the CPU resource. Ideally, if we send the same statements to the database twice, then we want the database to re-use the first statement access plan, we can use the PreparedStateMent object to get this effect.

Here, there is a major feature to distinguish PreparedStatement from its super-class statement: Unlike Statement, a SQL statement is provided when you create PreparedStatement. Then send it to DBMS immediately, compile this statement there. Thus, PreparedStatement is actually associated as a channel and the connection and the compiled SQL statement. So, what is its advantage? If you need to use the same query or similar query of different parameters multiple times, you can use the preparedStatement, statement, just compile and optimize it once by DBMS. Compared with normal Statement, you need to recompile each time you use the same SQL statement.

You can also create PreparedStatement through the Connection method. The following code shows how to create a parameterized SQL statement with three input parameters.

PreparedStatement prepareUpdateprice = con.preparestatement

"UPDATE SELLS SET price =? Where bar =? And beer =?");

Note that Java serialization does not support query languages ​​similar to SQL. The only way to use Java serialization access object properties is to deserialize the object and call the Getter / Accessor method on the object. A complete object may be expensive in the calculation, especially in the lifetime of the program, the application needs to be repeatedly executed.

You need to provide a value to the parameter before executing pre previousStatement. It can be implemented by calling the setxxx () method defined in preparedStatement. The most common method is setint (), setfloat (), setdouble (), and setString (). These values ​​need to be set before each preparative declaration.

Executing statements and querying the SQL statement in the JDBC varies depending on the purpose of the SQL statement. DDL (Data Definition Language) statement (such as table establishment and table changing statements) and update table content are performed by using ExecuteUpdate (). List 2 contains an instance of an executeUpdate () statement.

Listing 2. ExecuteUpdate () in actual operation

Statement Stmt = con.createstatement ();

Stmt.executeUpdate ("CREATE TABLE SELLS"

(Bar Varchar2 (40), Beer Varchar2 (40), Price REAL ");

Stmt.executeUpdate ("INSERT INTO SELLS"

"VALUES ('Bar of foo', 'budlite', 2.00)");

String Sqlstring = "CREATE TABLE BARS"

"(Name Varchar2 (40), Address Varchar2 (80), License Int";

Stmt.executeUpdate (Sqlstring);

We will perform preparedStatement through the previously inserted parameter (as shown above), then call ExecuteUpdate (), as shown below:

INT n = prepareUpdateprice.executeUpdate (); In contrast, the query is expected to return a row as its result and does not change the status of the database. Here is a corresponding method called ExecuteQuery (), its return value is a resultset object, as shown in Listing 3.

Listing 3. Execute a query

String bar, beer;

Float Price;

ResultSet RS = Stmt.executeQuery ("SELECT * from Sells");

While (rs.next ()) {

Bar = rs.getstring ("bar");

Beer = rs.getstring ("beer");

Price = rs.getfloat ("price");

System.out.println (Bar "Sells" Beer "for" Price "DOLLARS.");

}

Since the routines generated by the query are included in the variable RS, the variable is an instance of the Resultset. Collections are not too much for us, unless we can access the properties in each row and each row. ResultSet provides a cursor that can be accessed in turn. The cursor was originally placed in the position before the first line. Each method call will cause the cursor to move down. If the row exists, return true, or if there is no remaining row, return false.

We can use the appropriate type of getxxx () to retrieve the properties of a row. In the previous example, we use the getString () and getFloat () methods to access column values. Note that we provide the name of the column that is expected to be used as a parameter of the method; we can specify the list number instead of the column name. The column number of the first column retrieved is 1, and the second list is 2, and it is pushed according to the class.

When using preparedStatement, you can perform the query by the previously inserted parameter value, then calling ExecuteQuery (), as shown below:

ResultSet RS = prepareUpdateprice.executeQuery ();

About access to the ResultSet JDBC also provides a series of methods for discovering the location in the result set: getRow (), isfirst (), ISBEFOREFIRST (), islast (), and isafterlast ().

There are also some ways to allow the rolling cursor to free access to any line of the result set. By default, the cursor only scroll forward and is read-only. When you create a statement for Connection, you can change the RSULTSET's type to a more flexible scrollable or update model as follows:

Statement Stmt = con.createstatement (ResultSet.Type_forward_only, resultset.concur_read_only);

ResultSet RS = Stmt.executeQuery ("SELECT * from Sells");

Different types of types: type_forward_only, type_scroll_insensitive and type_scroll_sensitive. You can select whether the cursor is read-only by using the concur_read_only and the concur_updatable option. For the default cursor, you can scroll forward it before using rs.next (). For rolling cursors, you have more options as follows: rs.absolute (3); //moves to the third Retrieved Row

rs.previous (); //moves back one row in The Retrieved Result Set

Rs.RELATIVE (2); // Moves Forward Two Rows in The Retrieved Result Set

Rs.relative (-3); // Moves Back Three Rows in The Retrieved Result Set

For the work mode of the rolling cursor, there are more detailed descriptions. Although the rolling cursor is useful for a particular application, it leads to great performance loss, so it should be limited and cautious. You can find more information about the scrolling Resultset in the Reference Information Section.

There is no mechanism corresponding to the JDBC's ResultSet in serialization. Serialization is different from the view of the data of the underlying layer. JDBC (usually) assumes that the underlying data is a relational structure; while serialization assumes that the underlying data is an object map. There are significant differences in the underlying data structure of the two techniques. The JDBC's SET structure cannot be naturally mapped to the serialized object map structure, and vice versa. When a Java object is pulled by using serialization sempping, the underlying structure of the data becomes a byte stream, which shows the association between the various internal objects of the core object already serialized.

The RESULTSET navigation in the JDBC is from a SET element to other elements, and in object serialization, this is impossible because serialization involves an object association, rather than encapsulating a set of lines into an entity collection . Therefore, Java object serialization cannot provide you with your ability to access data separate parts separately in this way.

Transaction JDBC allows the SQL statement to be combined to a single transaction. Therefore, we can ensure the ACID attribute by using JDBC transaction characteristics.

Connection object performs transaction control. When a connection is established, the connection is automatically submitted by default. This means that each SQL statement itself is as seen as a transaction, and a completion will be submitted.

Auto Submit mode can be turned on or off with the following method:

Con.SetAutocommit (False);

Con.SetAutocommit (TRUE);

Once automatic submission is closed, the SQL statement cannot be submitted unless you submit the statement by calling commit (), otherwise you cannot submit the SQL statement (ie, the database will not be updated lastuated). We can call rollback () rollback transactions before committing, and restore the most recent commit value (before trying to update).

We can also set the desired transaction isolation level. For example, we can set the transaction isolation level to transaction_read_committed, which makes it allows access to it before the value is submitted. And ban dirty reading. Five such values ​​are provided for the isolation level in the Connection interface. By default, the isolation level is serialized. JDBC allows us to discover what transaction isolation levels set (using the GetTransactioniSolation () method for setting the appropriate level (using the setTransactioniSolaion () method using the Connection). Rollback usually uses the abnormal processing capability of Java language. This combination provides a simple and efficient mechanism for processing data integrity. In the next section, we will study how to use JDBC to perform errors.

Note that Java object serialization does not directly support transaction management. If you are using serialization, you will need to get this effect by using other APIs, such as JTA. However, in order to obtain the effect of the transaction isolation, you can choose to synchronize the serialized object when an update is performed, as shown below:

SYNCHRONIZED (my_deserialized_Object) {

// Perform the Updates ETC ...

}

There are always some errors in the software program that uses an exception handling error. Typically, the database program is a critical application, and it is necessary to properly capture and handle errors. The program should be restored and let the database are in some kind of state. Combining rollback to Java anomalous handler is a simple way to achieve this requirement.

Access Server (Database) Customer (program) needs to be able to identify all errors returned from the server. JDBC access this information by providing two levels of error conditions: SQLEXCEPTION and SQLWARNING. SQLException is Java exception, which will terminate the application (if not processed). Sqlwarning is a subclass of SQLException, but they represent non-fatal errors or unexpected conditions, so they can ignore them.

In Java code, you want to throw an exception or a warning statement in the TRY block. If the statement in the TRY block throws an exception or warning, you can capture it in a corresponding CATCH statement. Each capture statement pointed out that it is ready to capture an exception.

In other words, if the data type is correct, the database size exceeds its spatial limit and cannot establish a new table, it may throw an exception. Sqlwarning can be obtained from the Connection, Statement, and the ResultSet object. Each object is just a recent SQLWarning. Therefore, if other statements are performed via the Statement object, all early warnings will be discarded. Listing 4 illustrates the use of SqlWarning.

Listing 4. Sqlwarnings in actual operation

ResultSet RS = Stmt.executeQuery ("SELECT BAR from Sells");

Sqlwarning warn = stmt.getwarnings ();

IF (Warn! = NULL)

System.out.println ("Message:" Warn.getMessage ());

Sqlwarning Warning = rs.getwarnings ();

IF (Warning! = NULL)

Warning = warning.getnextwarning (); if (warning! = null)

System.out.println ("Message:" Warn.getMessage ());

In fact, SqlWarning is more rare to some extent than SQLException. The most common is the DataTruncation warning, which indicates a problem when reading or writing data from a database.

Java does not provide a particular exception class used by serialization. Most exceptions occurring when serialization are related to the executed I / O operation, and therefore, in these cases, I / O exception classes will meet the requirements.

Batch JDBC 2.0 provides a powerful API for batch. Batch allows you to accumulate a set of SQL statements and send them and processed together. A typical batch is the bank app, which updates many accounts every other hour. Batch is a powerful feature in reducing the number of round trips from Java code to the database.

The STATEMENT interface provides the AddBatch (String) method to add SQL statements to a batch. Once all SQL statements have been added to the batch, you can use the ExecuteBatch () method to perform them.

Then, use the executebatch () method to execute the SQL statement and return an array of int values. The array contains the number of rows affected by each statement. Playing the SELECT statement or other returns of the SQL statement in a batch will cause SQLEXCEPTION.

List 5 lists a simple instance using java.sql.statement for batch.

Listing 5. Batch of actual operation

Statement Stmt = conn.createstatement ();

Stmt.Insert ("delete from users");

Stmt.insert ("INSERT INTO Users VALUES ('Rod', 37, 'Circle');

Stmt.Insert ("INSERT INTO Uses VALUES"); "");

Stmt.insert ("Insert Into Users VALUES"); ");

Int [] counts = stmt.executebatch ();

When you don't know the number of specific statements, the batch is a good way to handle SQL code. For example, if you try to insert 100 records without using a batch, performance may be affected. If you write a script, add 10,000 records, then the situation will become worse. Adding batch can help improve performance, the latter can even improve the readability of the code.

Java object serialization does not support batch processing. Usually, serialization is applied on a range (contact diagram) of an object, in which case batch is meaningless. Therefore, batch processing provides you with certain flexibility in timing and packets of data updates, and these are not necessarily available for serialization.

Calling the stored procedure stored procedure from the Java code is a set of SQL statements, which establishes a logical unit and performs a specific task. You can use a stored procedure to encapsulate a set of operations or queries, which will be executed on a database server. The stored procedure is compiled and stored in the database server. Therefore, each time the stored procedure is called, DBMS will reuse the compiled binary code, so the execution speed will be faster.

JDBC allows you to call the database stored procedure from the Java application. The first step is to create a CallableStatement object. Like Statement and PreparedStatement objects, this operation is done with an open Connection object. The CallableStatement object contains calls to stored procedures; but it does not contain stored procedures themselves. The first line of code in Listing 6 establishes a call to the stored procedure show_account using the CON connection. The part of the waveform parentheses is a syntax of the stored procedure. When the driver encounters {Call show_account}, it translates the escape syntax into the local SQL used by the database, which calls the stored procedure named show_account. Listing 6. Storage procedures in actual operation

Callablestatement cs = con.preparecall ("{call show_account (?)}");

Cs.setint (1, myaccountnumber);

ResultSet RS = cs.executeQuery ();

Suppose the stored procedure show_account in Sybase contains the code shown in List 7.

Listing 7. Show_account Stored Procedure

Create Procedure Show_account (@Acc Int)

AS

Begin

SELECT Balance from user_accounts where account_no = @Acc

End

ResultSet RS looks similar to:

Balance

----------------

12000.95

Note that the method used to perform CS is ExecuteQuery (), since the stored procedure of the CS call contains only one query, there is only one result set. If the process contains only one update or a DDL statement, the executeUpdate () method will be used. However, sometimes there is a case where the stored procedure contains multiple SQL statements. In this case, it will generate a plurality of result sets, multiple update counts, or some combination of the result set and update counts. Therefore, you should use the Execute () method to perform CallableStatement.

The CallableStatement class is a subclass of PreparedStatement, so the CallableStatement object can accept the same parameters as the PreparedStatement object. Moreover, the callablestatement object accepts the output parameters and uses the parameter for input and output. The inout parameter and execute () method are usually rarely used. To handle the OUT parameters, you need to register the OUT parameter to the stored procedure by using the RegisterOutparameter (int, int) method.

For example, we assume that the GET_ACCOUNT process contains the code in the list 8.

Listing 8. Get_account

Create Procedure Get_account (@ACC INT, @Balance Float Output)

AS

Begin

SELECT @balance = Balance from user_accounts where account_no = @Acc

End

In this example, the parameter Balance is declared an OUT parameter. Now, the JDBC code called the process is shown in Listing 9.

Listing 9. Calling a DDBC code for a stored procedure

Callablestatement csmt = con?preparecall ("{get_account (?,?)"); Csmt.setint (1, youraccountnumber);

CSMt.RegisterOutparamter (2, java.sql.types.float);

Csmt.execute ();

When you are serialization in Java, you don't need to access any external systems such as DBMS. In other words, serialization is a pure Java language phenomenon, which does not involve the compiled code in an external environment. Therefore, there is no mechanism corresponding to the CallaBleStatement object in serialization. This means that you cannot transfer data processing to an external system or component, although these systems or components may be more suitable for it.

After reading this article, we hope that you agree that JDBC is much better than Java objects for data management and persistence.

JDBC is an excellent API for accessing data storage. The best thing for JDBC is that it provides a single API collection to access multiple data sources. Users only need to learn an API collection, you can access any data sources, which can be relational, layered or any other format. What you need is just a JDBC driver and connect it to the target data source. JDBC has worked a lot of work, encapsulated all technical details into a software package, thereby liberating programmers from vendor-specific 桎梏.

Table 1 compares various characteristics of JDBC and Java object serialization.

Table 1. JDBC serialization of Java

Object Serialization JDBC Data Manage Using File System Storage Sequence Object Format. These systems do not include a specific data management system. Serialized objects (stored in a normal file) is usually managed by the underlying OS in its own special way. Use an EAI / database to store data. EAI or database has a database management system (DBMS) specified in the data source. JDBC is an interface to send requests to JVM and DBMS between DBMS. JDBC itself does not have any data management functions. The data structure of the underlying data structure is an object map. Serialization writes the status of the Java object to the file system. The underlying data structure can be a relational, hierarchical, or a network shape. But the logical view of the data is usually a table. Data definition data definitions relate to the use of serialized semantics to establish a sequentialized object and persisted the object. Data definitions relate to the establishment of the necessary tables in the target data store and provide a clear definition of the domain-level relationship between the entities. This is usually done by using the software provided by the target DBMS. Data Retrieval Data Retrieval involves reverse sequence-based objects and uses accessient methods to read the properties of objects. DBMS provides a special data sub-language to retrieve data. The statement written in this data sub-language can be passed to the target data source through the JDBC API. DBMS is responsible for verifying, executing, and returning the result of the statement. Safety has no well-defined security mechanism. However, the underlying OS can provide security for serialized files. DBMS provides a wide range of security features. It can complete authentication and authorization. The JDBC API needs to send a certificate to the target DBMS before accessing or operating the data on the DBMS. The transaction does not have a specific transaction control mechanism that can be used. By using other J2EE APIs, such as JTA or JTs, the transactions can be maintained on the program. DBMS provides complex transaction management. The JDBC API provides useful ways to submit and rollback transactions. Concurrent control does not have a specific concurrent control mechanism that can be used. However, the effect of concurrent control can be obtained by using synchronization techniques in the Java language. DBMS offers a variety of levels of transaction isolation. You can use the JDBC API method to select a specific level of isolation.

Java object serialization and JDBC are two of many data persistence mechanisms in the Java technology. When needed between multiple JVMs (such as sharing data with RMI, with RMI, with the RMI, the value transfer mechanism is shared), the sequence is most suitable. However, Java serialization does not apply to corporate data, and it is necessary to organize these data in a well-defined structure. In such a business system, you need to share data between multiple systems and subsystems, and these systems are not necessarily compatible with Java language. In this case, the sequence of objects cannot work at all. JDBC provides a public API to access heterogeneous data storage. It is an adhesive between JVM and target DBMS. It provides a programming method for accessing data storage and maintenance of enterprise data using Java platform. However, all the code required to perform CRUD operations is written by the developer.

In order to use JDBC in an enterprise environment, architectural designers need to analyze data in their enterprises and develop a framework for data persistence. Since the mechanism for using JDBC persistent data is not related to the business problems you want to solve, it is strongly recommended to separate the data persistence layer to the commercial logic of the application. Design patterns are very helpful for designing this framework.

转载请注明原文地址:https://www.9cbs.com/read-123469.html

New Post(0)