Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 46 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
46
Dung lượng
1,22 MB
Nội dung
Element Description batch-mode Batch-mode is used only if a database supports it. Each implementation of the mode is database-dependent. Batch-mode can be changed at run- time using the PersistenceBroker.serviceConnectionManager .setBatchMode( ) useAutoCommit Affects the way OJB uses the auto-commit mode. There are three modes; the default mode is 1. 0 — turns auto-commit off. 1 — sets auto-commit explicitly to true when a connection is created, and temporarily sets it to false when necessary (default). 2 — sets auto-commit explicitly to false when a connection is created. ignoreAutoCommit If set to false, OJB will ignore any exceptions that are thrown from the Exceptions use of auto-commit. Home.jsp This is the default page that is displayed to users when they access the message board sample Web application. When this page is displayed, a list of currently existing messages is shown to the user. This page also provides links to the user to enable the viewing of a specific message in greater detail or to delete a specific message from the database. The code to perform all this functionality is embedded within Home.jsp. In order to retrieve the messages and display them to the user, you need to know how many messages exist in the database first. If none are available, then there is no need to waste your time trying to iterate through non-existent messages. The following code shows how to use the PersistenceBroker API to retrieve the number of messages that exist in the database: PersistenceBroker broker; public int getCount() { try { // Create a PersistenceBroker object using the // PersistenceBrokerFactory. broker = PersistenceBrokerFactory.defaultPersistenceBroker(); // Construct a query to be issued Query query = new QueryByCriteria(Message.class, null); // Ask the broker to retrieve the extent collection Collection allMessages = broker.getCollectionByQuery(query); // If there are messages then return the number of messages if (allMessages != null) { broker.close(); PersistenceBrokerFactory.releaseAllInstances(); return allMessages.size(); } else { 100 Chapter 4 07 469513 Ch04.qxd 1/16/04 11:03 AM Page 100 broker.close(); PersistenceBrokerFactory.releaseAllInstances(); return 0; } } catch (Exception e) { System.out.println(e); e.printStackTrace(); broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } return 0; } Once you have the number of messages that exist in the database, you can then retrieve each one inde- pendently to exhibit to the user. You need to use getMessage to retrieve the specified message from the server. The getMessage method is shown in the following code: public Message getMessage(String sIndex, String sUserIP) { Message msgFound = null; try { // Create a PersistenceBroker object using the // PersistenceBrokerFactory broker = PersistenceBrokerFactory.defaultPersistenceBroker(); // Construct a query to be issued Query query = new QueryByCriteria(Message.class, null); // Ask the broker to retrieve the extent collection Collection allMessages = broker.getCollectionByQuery(query); // Now iterate through the results java.util.Iterator iter = allMessages.iterator(); int nIndex = Integer.parseInt(sIndex); int i = 0; // Search for the message we are looking for while (iter.hasNext()) { i++; // If we found our message exit the loop if (i == nIndex) { msgFound = (Message) iter.next(); break; } else { iter.next(); } } Once you have found a message, you need to create a Viewer object that will let the message know that it has been viewed. The new Viewer object is then saved to the Message object, which is in turn saved to the data source using the store method of the broker object: 101 Object to Relational Mapping with Apache OJB 07 469513 Ch04.qxd 1/16/04 11:03 AM Page 101 // If we have a message, return it if (msgFound != null) { // Construct a viewer object to show that this message has // been accessed Vector tmpvVwrs = msgFound.getViewers(); Viewer tmpView = new Viewer(); Calendar clNow = Calendar.getInstance(); tmpView.setIP(sUserIP); tmpView.setDate( Integer.toString((clNow.get(Calendar.MONTH) + 1)) + “/” + Integer.toString(clNow.get(Calendar.DAY_OF_MONTH)) + “/” + Integer.toString(clNow.get(Calendar.YEAR)) ); tmpView.setID(msgFound.getID()); tmpvVwrs.add(tmpView); // Save the new Viewer to the Message class msgFound.setViewers(tmpvVwrs); try { // Begin transaction broker.beginTransaction(); // Store the new persistent making it persistent broker.store(msgFound); // Finally commit the transaction broker.commitTransaction(); } catch (PersistenceBrokerException ex) { // Rollback on error broker.abortTransaction(); System.out.println(ex.getMessage()); ex.printStackTrace(); broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } else { broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } } catch (Exception e) { System.out.println(e); e.printStackTrace(); broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } return msgFound; } 102 Chapter 4 07 469513 Ch04.qxd 1/16/04 11:03 AM Page 102 From the getCount and getMessage examples, you can perceive that there is a systematic approach to issuing queries using the PersistenceBroker API. The following sequence shows the generic steps in issuing a query utilizing the PBAPI: 1. Obtain a PersistenceBroker by using the PersistenceBrokerFactory defaultPersistenceBroker method: broker = PersistenceBrokerFactory.defaultPersistenceBroker(); 2. Construct a query using a class that is mapped in the OJB metadata repository: Query query = new QueryByCriteria(Message.class, null); 3. Ask the broker to retrieve a collection of objects based on the query statement: Collection allMessages = broker.getCollectionByQuery(query); 4. Iterate through the collection results and manipulate the objects you want to change: java.util.Iterator iter = allMessages.iterator(); 5. After changing the objects, you then need to store them back in the database. This requires you to issue a transaction method and a store method: broker.beginTransaction(); broker.store(msgObject); broker.commitTransaction(); 6. Finally, you need to close the broker and release any instances that you created from the broker pool: broker.close(); PersistenceBrokerFactory.releaseAllInstances(); To delete a message, you would use the same general code that was depicted in the getMessage method, but rather than store the object with the broker.store function, you would execute a delete on the object: try { broker.beginTransaction(); broker.delete(msgObject); // Delete the Message broker.commitTransaction(); etc. In the preceding code, you now have all the necessary functionality to execute the Home.JSP program and see the results. Figure 4.3 shows what the OJB message board looks like after it has retrieved all the messages that exist in a database. The Home.jsp code is now complete and functioning. The following section describes how to add a mes- sage to a database using the PersistenceBroker API. Add.jsp will demonstrate this functionality. 103 Object to Relational Mapping with Apache OJB 07 469513 Ch04.qxd 1/16/04 11:03 AM Page 103 Figure 4.3 Add.jsp This page is accessed when the user wants to submit a new article to the message board. A form is shown to the user requiring them to enter information in several fields. Once the user has filled out the form and pressed the Submit button, the information is actually submitted to the same Add.jsp page, which displays an embedded note to the user informing them that their article has been submitted to the message board. The majority of the code is similar to the code in previous examples; the main exception is that you need to construct the Message object and fill it with data before you can persistently store it. Another point to note here is that when the objects are stored, the PersistenceBroker API will automatically create a unique ID for the object(s) and store it in the database. Figure 4.4 exemplifies the Add.jsp article sub- mission form. The addMessage method is called when the user clicks the Submit button. The addMessage method processes the form data, converts it into a Message object, and then uses the PBAPI to store the object in the database. The following code displays the addMessage code: public Message addMessage( String sSubmitter, String sSubject, String sMessage) { Message msgToStore = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); // Create Message to store msgToStore = new Message(); 104 Chapter 4 07 469513 Ch04.qxd 1/16/04 11:03 AM Page 104 // Add submitter to message msgToStore.setSubmitter(sSubmitter); // Add subject to message msgToStore.setSubject(sSubject); // Add article to message msgToStore.setMessage(sMessage); Calendar clNow = Calendar.getInstance(); // Set the date msgToStore.setDate( Integer.toString((clNow.get(Calendar.MONTH) + 1)) + “/” + Integer.toString(clNow.get(Calendar.DAY_OF_MONTH)) + “/” + Integer.toString(clNow.get(Calendar.YEAR))); Figure 4.4 The broker.store method performs the actual persisting of the Message object, msgToStore, to the data source: // now perform persistence operations try { broker.beginTransaction(); 105 Object to Relational Mapping with Apache OJB 07 469513 Ch04.qxd 1/16/04 11:03 AM Page 105 // Store the new object broker.store(msgToStore); broker.commitTransaction(); } catch (PersistenceBrokerException ex) { broker.abortTransaction(); System.out.println(ex.getMessage()); ex.printStackTrace(); broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } catch(Exception e) { System.out.println(e); broker.close(); PersistenceBrokerFactory.releaseAllInstances(); } return msgToStore; } View.jsp This is the final JSP in the message board example. It does not introduce any new code and utilizes the same getMessage method found in Home.jsp. What it does differently is display the full contents of a specific message to the user. Figure 4.5 is a screenshot of what the user would see when a message is accessed with View.jsp. Figure 4.5 106 Chapter 4 07 469513 Ch04.qxd 1/16/04 11:04 AM Page 106 Developing with the ODMG API This section briefly describes how to develop OJB applications using the ODMG API. OJB has created its own implementation of the ODMG APIs, which it stores in the package org.apache.ojb.odmg. In order to use the vast feature set of ODMG, you have to deal directly with an object that acts as the main entry point of the ODMG APIs. This object is distinguished by the interface org.odmg.Implementation, which enables you to obtain OQL objects, database objects, persistent collection objects, and transaction objects. The good news is that if you have used ODMG before with non-OJB applications, the code will be very similar to what you have created in the past, as all vendors must implement the org.odmg.Implementation interface. The main difference is learning how OJB provides you access to the ODMG object. The examples that follow are based on creating the same type of functionality seen in the PersistenceBroker API message board example, but utilizing ODMG instead. The core functionality covered here includes opening a database, deleting and retrieving objects, and updating and storing objects. Opening a Database As stated earlier, OJB has its own specific implementation of the org.odmg.Implementation interface; this is simply org.apache.ojb.odmg.OJB. Now we need to obtain an instance of this class using the static factory method getInstance. Using this instance, we can now open or create an ODMG database ( org.odmg.Database). The complete code follows: import org.apache.ojb.odmg.OJB; import org.odmg.Database; import org.odmg.Implementation; import org.odmg.ODMGException; public Database open() { // Obtain an ODMG object of type org.odmg.Implementation Implementation odmgObject = OJB.getInstance(); Database odmgDB = odmgObject.newDatabase(); //open database try { odmgDB.open(“repository.xml”, Database.OPEN_READ_WRITE); } catch (ODMGException e) { e.printStackTrace(); } return odmgDB; } Retrieving Objects Obtaining objects using ODMG is quite a bit different than using the PersistenceBroker API. You need to use the Object Query Language (OQL) designated by ODMG and set up query statements, which are very similar to SQL statements. With the PBAPI, you issue queries directly on the objects with QueryByCriteria methods. You need to obtain an OQLQuery object first, and then create a query state- ment and execute it. This returns the Message objects in a DList, which you can later iterate through when you are ready to process them. The following example shows the complete code for retrieving objects using ODMG: 107 Object to Relational Mapping with Apache OJB 07 469513 Ch04.qxd 1/16/04 11:04 AM Page 107 import org.apache.ojb.odmg.OJB; import org.odmg.DList; public DList getAllMessages() { try { // Begin a transaction Transaction trans = odmgObject.newTransaction(); trans.begin(); // Obtain an OQLQuery object OQLQuery query = odmgObject.newOQLQuery(); // Create the OQL select statement query.create(“select allmessages from “ + Message.class.getName()); // Execute the query DList allMessages = (DList) query.execute(); // Commit the transaction trans.commit(); // Return the DList of messages return allMessages; } catch (Exception e) { System.out.println(e); e.printStackTrace(); } return null; } Storing Objects Storing objects is extremely easy with the ODMG API. All you need to do is start a new transaction, create a write lock on the object to store, and then commit the transaction. The following example demonstrates the code to store objects with ODMG: public void storeObject(Message msg) { Transaction trans = null; try { // Obtain a new transaction object trans = odmgObject.newTransaction(); trans.begin(); // We need to write lock the new object trans.lock(msg, Transaction.WRITE); // Now we commit the transaction trans.commit(); } catch( Exception e ) { System.out.println(e); e.printStackTrace(System.out); } } 108 Chapter 4 07 469513 Ch04.qxd 1/16/04 11:04 AM Page 108 Updating Objects Updating objects requires more interaction than storing objects. In order to update an existing object, you have to execute a query that can find the specific object that you are looking for. Once the object is obtained, you then invoke a write lock on the object. The final steps are to update the necessary data contained in the object and then commit the transaction. Following is the complete code needed for updating objects using ODMG: public void update(Message msg) { Transaction trans = null; // Create a query to find a message with the specific ID String oqlQuery = “select * from “ + Message.class.getName() + “ where id = “ + msg.getID(); // Get the current database Database odmgDB = odmgObject.getDatabase(null); try { trans = odmgObject.newTransaction(); trans.begin(); OQLQuery query = odmgObject.newOQLQuery(); query.create(oqlQuery); // Execute the query DList dlMessages = (DList) query.execute(); // Retrieve the message Message msgFound = (Message) dlMessages.get(0); // Set write lock trans.lock(msgFound, Transaction.WRITE); // Edit message subject line msgFound.setSubject(“The subject has been edited”); // Commit transaction trans.commit(); } catch (Exception e) { // RollBack trans.abort(); System.out.println(e); e.printStackTrace(System.out); } } Deleting Objects Deleting objects with ODMG API requires the same methods as updating objects. First, you have to obtain the object you want to delete. Second, you need to mark it for deletion with Database.deletePersistent(Object). Third, you simply commit the transaction and the delete operation is carried out. The following example displays the code for deleting objects: 109 Object to Relational Mapping with Apache OJB 07 469513 Ch04.qxd 1/16/04 11:04 AM Page 109 [...]... browser With the HTTP client, the content management system can be managed easily through a Web-based interface This falls right into play with portal development and is probably the best approach for administering content from a portal perspective The final component of the client layer is a Java Application Client A Java Application Client can be created to utilize Slide’s API layer directly without... when building Java portals The transaction management architecture is shown in Figure 5.3 Clients Slide API Helper components Transaction Management Layer Store API Data sources Data Stores Figure 5.3 122 Content Management with Jakarta’s Slide Transaction management is key to a successful content management framework — without it, data can easily become corrupted or out of sync Slide uses Java transaction... jakarta-regexp-1.2.jar 1.2 jcs-1.0-dev.jar* 1.0-dev jta-1.0.1.jar* 1.0.1 junit-3.8.jar 3.8 log4j-1.2.6.jar* 1.2.6 p6spy-1.0.jar* 1.0 servletapi-2.2.jar 2.2 torque-3.0.jar 1.3 xalan-2 .4. jar 2 .4 xerces-2.0.2.jar* 2.0.2 113 Chapter 4 Metadata Files Two main files are needed in order for OJB to run correctly: ❑ The repository.xml file and any resources it points to are needed for deployment ❑ The ojb.properties file is... supported JDBC data types and their Java equivalent JDBC Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java. math.BigDecimal DECIMAL java. math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float DOUBLE double FLOAT double BINARY byte[] VARBINARY byte[] LONGVARBINARY byte[] DATE java. sql.Date TIME java. sql.Time TIMESTAMP java. sql.Timestamp CLOB Clob BLOB Blob... the development task you are presented with From a portal development standpoint, you would most likely choose either the HTTP client approach or the WebDAV approach for managing content, as both lend themselves to easy remote management capabilities The standalone Java application approach requires more configurations in order to get the application up and running If you want a portable standalone Java. .. on Java Web Start WebDAV client HTTP client Java Application Client Server WebDAV servlet Slide API Figure 5.1 119 Chapter 5 The server layer enables the client layer to communicate with it through one of two methods One method is to use the WebDAV servlet for communication WebDAV clients and HTTP clients use this approach The second method is for the client to communicate directly with the Slide API. .. Slide API There are two methods for doing this One is to use the WebDAV servlet for communication As described in the preceding section, the WebDAV client and HTTP client interface with the WebDAV servlet for communication purposes The second method is to use a standalone Java application that will directly access the Slide API layer The Slide API layer provides access to the content management Java. .. DISTINCT mapping underlying type STRUCT Struct REF Ref JAVA_ OBJECT 112 Java Equivalent Java class Object to Relational Mapping with Apache OJB Deploying OJB Applications Deploying OJB applications requires specific knowledge of the OJB resources and configuration files that are needed to run an OJB-supported application This section describes the resources and configurations and explains how each fits... the domain log (java. lang.Object data, int level) 1 34 Provides an enumeration of namespaces contained in the domain A log method for inserting information into the domain’s log file Content Management with Jakarta’s Slide Slide API Layer The final component of the Slide architecture is a component that should already be familiar to you from previous discussions The Slide API layer (SLAPIL) is intertwined... data transactions 120 Content Management with Jakarta’s Slide Java application WebDAV servlet Slide API Security helper Lock helper JNI Content helper JTA Layer JDBC File System Data sources LDAP Figure 5.2 121 Chapter 5 Transaction Management Slide implements a very robust transaction management system Transaction management is very important when dealing with content management, especially in a system . Figure 4. 5 is a screenshot of what the user would see when a message is accessed with View.jsp. Figure 4. 5 106 Chapter 4 07 46 9513 Ch 04. qxd 1/16/ 04 11: 04 AM Page 106 Developing with the ODMG API This. Slide. 115 Object to Relational Mapping with Apache OJB 07 46 9513 Ch 04. qxd 1/16/ 04 11: 04 AM Page 115 07 46 9513 Ch 04. qxd 1/16/ 04 11: 04 AM Page 116 Content Management with Jakarta’s Slide Jakarta’s Slide. tool. 1 14 Chapter 4 07 46 9513 Ch 04. qxd 1/16/ 04 11: 04 AM Page 1 14 This chapter described Object-to-Relational mapping and then explained the main features of OJB. Next, it covered how to use OJB’s API