Data management and data persistence in J2EE applications

xiaoxiao2021-03-19  187

Http://kingreturn.blogchina.com/1528658.html

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 as shown below: Package Java.io; public interface serializable {} You can see, java.io. The 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.

List 1. MySerializableObject.javaimport 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 setProperty1 (String val) { property1 = val;} public String getProperty2 () {return property2;} public void setProperty2 (String val) {property2 = val;} private void writeObject (ObjectOutputStream out) throws IOException {out.writeObject (getProperty1 ()); out.writeObject (getProperty2 ());} private void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException {setProperty1 ((String) in.readObject ()); setProperty2 ((String) in.readObject ());}} achieved without their writeObject ( ...) and readObject (...) methods to perform serialization; Java runtime environment has the default implementation that allows 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. Typically, serialization is not the best choice for applications: Managing several trigural storage data frequently update sequential objects for storage enterprise data, sequentialization is an error selection because: Sequence The byte stream is only readable to 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 () The Java object serialization does not require this step, because use serialization to perform persistence operations and do not need DBMS. Serialization is a file-based mechanism; therefore, before serialization of an object, you need to open an I / O stream in the target file system. Creating JDBC Statement and PreparedStatement You can send SQL statements to database management with JDBC Statement objects System (DBMS) and should not be confused with the SQL statement. The JDBC Statement object is associated with the open connection, not with any separate SQL statement. You can view the JDBC Statement object as a connection. Channel, transfer one or more (your request) SQL statement to DBMS. In order to create a Statement object, you need a mobile connection. By using the CONNECTION object CON - below the CONNECTION object CON - below to complete this Work .Statement Stmt = Con.CreateStatement (); So far, we already have a statement object, but have not passed the object to the SQL statement of DBMS. When the database receives the statement, the database engine first analyzes the statement and Find a syntax error. Once the statement is completed, the database must calculate the most effective way to perform it. This may be very expensive. Database will check which index can provide help, if there is such an index, or check Whether it should completely read all rows in the table. Database for data for data, identify the best execution method. Once the query plan is created, the database engine can execute it. Generate such a plan will take up the CPU resources. Ideally If we send the same statement to the database twice, then we hope that the database is re-use of the first statement access plan, we can use the PreparedStateMent object to get this effect. There is a major feature that will preparedStatement with its super class Statement. Different from: Unlike Statement, a SQL statement is provided when you create preparedStatement. Then send it to DBMS immediately, and compile this statement.

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 language 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 () Stmt.executeUpdate ("Create Table Sells" ("Create Table Sells" ("Create Table Sells" (40), BAR VARCHAR2 (40), BEER 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 previously inserted parameter values ​​(as shown above), then call ExecuteUpdate (), as follows: int N = prepareUpdateprice.executeUpdate () In contrast, the query is expected to return a line 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 = 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.");} Due to query The resulting rows are included in the variable RS, which is an example 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 follows: ResultSet RS = prepareUpdatePrice.executeQuery (); About access to the Resultset JDBC also provides a series of discovered you The method of the result is the location of the concentrated position: 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 shown below: Statement Stmt = con.createstatement (ResultSet.Type_forward_only, resultset.concur_read_only); ResultSet RS = Stmt. ExecuteQuery ("Select * from sales"); 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 rion.previous (); //moves back one row in the retrieved resultset.RELATIVE ( 2); // Moves Forward TWO ROWS IN THE RETRIEVED RESULT SETRS.RELATIVE (-3); // Moves Back Three Rows in The Retrieved Result Set For the Mode of Working, there are more detailed descriptions here. 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 opened or closed by following: Con.SetAutoCommit (true); Up to be submitted, unless you are explicitly submitted by calling commit (), otherwise you cannot submit SQL statements. (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 transaction isolation, you can choose to synchronize the serialized object when performing an update operation, as shown below: Synchronized_Object {// perform the Updates etc ...} Using an exception handling error software program There are some errors. 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. SQLWARNINGSRESULTSET 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 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 StMT = Conn.createStatement (); Stmt.insert ("INSERT INTO Users Values); Stmt.insert (" INSERT INTO Uses VALUES) " ); Stmt.insert ("INSERT INTO Users Values ​​('Jane', 33, 'Triangle'); Stmt.insert (" Insert Into Users Values ​​('Freddy', 29, 'Square') "); int ] counts = stmt.executebatch (); When you don't know the number of times the specific statement will run, 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 {callshow_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 procedure in actual operation Callablestatement cs = con?preparecall ("{call show_account (?)}); Cs.setint (1, myaccountnumber); ResultSet RS = cs.executeQuery (); assume Sybase in Sybase Process show_account contains the code shown in List 7. Listing 7. SHOW_ACCOUNT stored procedureCREATE PROCEDURE SHOW_ACCOUNT (@Acc int) ASBEGINSelect balance from USER_ACCOUNTS where Account_no = @AccENDResultSet rs looks like: balance ---------------- 12000.95 noted for The method of executing the 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_accountcreate procedure get_account (@acc int, @Balance Float output) asbeginselect @balance = balance from user_accounts where account_no = @accend In this instance, the parameter balance is declared as an OUT parameter. Now, the JDBC code called the process is shown in Listing 9. List 9. Calling a stored procedure JDBC code callablestatement csmt = con?preparecall ("{get_account (?,?)"); Csmt.setint (1, youraccountnumber); csmt.registeroutparamter (2, java.sql.types.flloat) ); csmt.execute (); When using Java serialization, it is not necessary to access any external system, 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 serialize the JDBC data management of Java serialized Objects Use the file system storage serialized 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.

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

New Post(0)