Persistence in Spring Author: Bruce A. Tate and Justin Gehtland

xiaoxiao2021-03-06  78

Persistence in Spring

By Bruce A. Tate and Justin Gehtland

Editor's note: It's usually better to solve problems with simplicity and finesse rather than muscle That's the premise behind the recently released Better, Faster, Lighter Java Its authors, Bruce Tate and Justin Gehtland, put this belief to the test in this two-.. part series on Spring, excerpted from Chapter 8 of their book. This week Bruce and Justin continue where they left off in part one, taking you through adding persistence to the Pet Store example, and looking at the area of ​​presentation logic in the Spring framework .

Add inistence

The CartItem object does not necessarily need to be persistent. On the other hand, you'd expect to pull products and categories from a database. J2EE application developers have long searched for a clean approach to persistence without much success. The best persistence frameworks allow transparency and do not invade the domain model. Spring lets you separate your transparent object from the data access layer. Spring then makes it easy to layer on persistence. you can use a JDBC abstraction layer, which abstracts away many of the tedious and error- prone aspects of JDBC, such as connection management and error handling. The Spring JDBC layer uses a feature called callback templates to pass control from your application to the framework. With this strategy, Spring removes the need to manage connections, result sets, and RDBMS -Specific Errors. this framework is useful when Want To Use JDBC Directly TO Process RELATIONAL QUERIES.

Often, you'd rather deal with objects instead of relations. Spring also has an appropriate model for transparent persistence. The jPetStore uses Spring's OR mapping layer, which provides a variety of prepackaged choices. Spring now supports mapping layers for basic JDBC DAO, Hibernate And JDO. this Example Uses a Dao Framework Called Ibatis SQL Maps TO IMPLEMENT A Spring Dao Layer.The Model

Each of the Spring Solutions Starts with a transparent Domain Model. EXAMPARE 8-3 Starts with The Transparent Model Object, A Product.

Example 8-3. Product.java

Public Class Product Implements Serializable {

Private string productId;

PRIVATE STRING CATEGORYID;

PRIVATE STRING NAME;

Private string description;

Public string getProductId () {return products

Public void setProductId (String Productid) {this.productid = productId.trim ();

Public string getcategoryId () {return categoryid;}

Public void setcategoryId (string categoryid) {this.categoryId = categoryId;

Public string getname () {return name;}

Public void setname (String name) {this.name = name;}

Public string getDescription;} {Return Description;

Public void setdescription (string description) {this.description = description;

Public string toString () {

Return getName ();

}

}

.. There's nothing special here It consists purely of properties, accessed through getters and setters, and one utility method, toString When you look into the jPetStore application, you'll find similar classes for each of the other persistent objects in the domain: Account , ORDER, Category, Item, and LineItem.

The mapping

As with Hibernate, the iBATIS SQL Maps framework has a mapping file. In it, each persistent property in your Java bean maps onto a single database column. Using SQL Maps, create all of your SQL within that mapping file as well, isolating all SQL To Your XML Mapping Files. EXAMPLE 8-4 Shows The XML Mapping Support for Product.example 8-4. Product.xml

[1]

[2]

[3]

[4]

Select Productid, Name, Descn, Category from Product Where ProductId = # Value #

[5]

Select Productid, Name, Descn, Category from Product Where Category = # Value #

[6]

Select ProductID, Name, Descn, Category from Product

Lower (name) Like #keywordList [] # or lower (category)

Like #keywordlist [] # or lower (descn) Like #keywordlist [] #

Here's what the annotations mean:

.

[2] Other Information About The Dao Layer, Like Caching Strategies, Also Belong in The Mapping File. Here, Ibatis Maintains a cache for 24 hours and flushes it.

[3] Each of these queries returns, of course, a product. This maping Ties Each Column of the result set to one of the fields in product.

[4] This SQL Statement Finds a Product, Given a ProductId.

[5] This SQL Statement Finds All Products in A Category. It Returns A List of Products.

[6] This SQL Statement is Dynamic. Ibatis Iterates Over The Keyword List and Forms A Dynamic Query.

.

The Dao Interface

Somehow, The Application Must Integrate with Both Spring and SQL Maps. The Application Ties The Two Concepts TOGETHER WIES The Two Interface, And A Concrete IMplementation. Example 8-5 is The interface.

Example 8-5. ProductDao.java

Public interface productda {

List getProductListBycategory (String CategoryId) THROWS DATAACCESSEXCEPTION;

List searchProductList (String Keywords) Throws DataAccessException;

Product GetProduct (String Productid) THROWS DATAACCESSEXCEPTION;

}

That's simple enough. You can see an interface for each of the queries defined in the mapping. Specifically, you can see an interface getProduct that finds a product by ID, one for getProductListByCategory that returns all products in a category, and one for the dynamic Query Based ON Keywords. Now The Dao throws Spring Exceptions; Any Logic That Uses The Dao Will Have Consistent Exceptions, Even IF You Later Decide To Change Implementations.The Dao Implementation

All That Remains Is To Implement The Interface with SQL Map. EXAMPLE 8-6 IS The SQL MAP IMPLEMENTATION for Product.

Example 8-6. SQLMAPPRODuCTDAO.JAVA

Public Class Sqlmapproductdao Extends Sqlmapdaosupport IMPLEments Productda {

[1] Public List GetProductListBycategory (String CategoryId) THROWS DATAACCESSEXCEPTION {

Return getSqlmapTemplate () .executeQueryforList ("getProductListBycategory",

}

[1] public product getProduct (String Productid) throws dataAccessException {

Return (Product) getSqlmapTemplate () .ExecuteQueryForObject ("getProduct", ProductID;

}

[1] Public List SearchProductList (String Keywords) throws dataAccessException {

Object ParameterObject = New ProductSearch (keywords);

Return getSqlmapTemplate () .executeQueryforList ("SearchProductList", ParameterObject);

}

/ * Inner Classes * /

[2] public static class productsearch {

Private list keywordlist = new arraylist ();

Public productSearch (String Keywords) {

StringTokenizer Splitter = New StringTokenizer (Keywords, "", FALSE);

While (splitter.hasmoretokens ()) {

THISKYWORDLIST.ADD ("%" splitter.nextToken () "%");

}

}

Public List getKeywordList () {

Return KeywordList;

}

}

}

Here's what the annotations mean:. [1] These methods provide the SQL Map implementation of the interface Other implementations might use Hibernate, JDO, or straight JDBC In this case, the getTemplate call instructs Spring to get the template for iBATIS SQL Map support. And Execute the appropriate query using the framework.

[2] I'm not a big fan of inner classes, but that's what they used to implement the keyword search. In this case, the inner class supports the searchProductList method by implementing getKeywordList. The inner class helps to organize the code base, Keeping All of The Support in One Location, with the rest of the dao mailmentation.

Now You've seen the mapping, the model, and the dao. You Have a fully personistent model. Next, access the dao layer with code. JPETSTORE FUNNELS All Dao Access Through a façade.

USING THE MODEL THROUGH A FAçade

Just As in Chapter 3, IT offs Sense To Have A Higher-Level Interface for a Model, Called The Façade. In this Case, The JpetStore Façade Serves Three Purposes:

CONSOLIDATES All of the Clients of The Data Access Layer. Presents A Single, Common User Interface for The Rest of the Applications. Serves as an attachment point for Other Services, Such As Transaction Support.

In this case, the façade is a very thin layer around all of the DAO Through configuration and method interceptors, Spring attaches declarative transaction support to the façade In this case, the façade is in two parts:... The interface and the implementation The Interface allows you to change the impacting the rest of the code. EXAMPLE 8-7 shows the interface.

Example 8-7. PetStoreFacade.java

Public interface petstorefacade {

Account getaccount (string username); Account getAccount (String UserName, String Password);

Void InsertAccount; Accent Account;

Void UpdateAccount; Acount Account;

List getusernamelist ();

List getcategorylist ();

Category getcategory (String CategoryID);

List getProductListBycategory (String CategoryID);

List searchProductList (String Keywords);

Product (String ProductID);

List GetItemlistByProduct (String ProductID);

Item GetItem (String ItemID);

Boolean IsteminStock (String ItemID);

Void InsertOrder;

Order GetOrder (int Order);

List getordersbyusername (String username);

}

Think of this interface as a consolidated list of every method that creates, reads, updates, or deletes any Pet Store object. Notice that you do not see every method from all of the DAO. You see only the methods that we wish to expose to the rest of the world. Also, notice the naming consistency within the interface. This is important because within our configuration file, you saw the transaction support configured to propagate methods beginning with get, search, update, or insert.

The implementation simply calls the underlying DAO to do the appropriate job. It must implement all of the methods in the interface. Example 8-8 is the implementation of the methods related to the ProductDAO.

Example 8-8. Excerpt fromPetStoreImpl.java

[1] Private productdao productda;

...

Public void setProductdao (ProductDao Productdao) {

THIS.PRODUCTDAO = PRODUCTDAO;

}

...

[2] Public List GetProductListBycategory (String CategoryId) {

Return this.ProductDao.getProductListBycategory (categoryID);

}

Public List searchProductList (String Keywords) {

Return this.ProductDao.SearchProductList (Keywords);

}

...

Here's what the annotations mean: [1] Shows the DAO access (includes the bold text) The Spring framework inserts the DAO into the façade using reflection That means the façade must support a set method and a private member variable...

[2] The Methods That Provide Data Access Use The underlying Dao To Do The Actual Work (Includes the bold text).

Of Course, I Haven't Shown The Implementation of All of The Interface's Methods. Theese is. The method................

First, the application context wired each DAO to the façade. Spring uses reflection and the bean factory to create the product DAO and set it using the setProductDAO API. To support this, the façade needs a variable to hold the DAO and a set method to Access it through reflection.

Second, the implementation is simple. The façade merely passes the request through to the model layer underneath. The ultimate implementation is much more powerful, though. The façade functions like an EJB session bean with respect to declarative transaction support. Through configuration, the POJO Becomes a Declarative Transaction Coordinator! It's Also a Central Point of Control for the entire database layer. All this remains is to configure the dao layer.

Configuration for the Dao Layer

Recall that you have seen only the configuration for the model. Example 8-9 shows the configuration of the data layer for a single database with simple transaction management. As you'd expect, you'll see the configuration of the JDBC driver and the Declarative of all of the dao beans.

Example 8-9. DataAccessContext-local.xml

[1]

Class = "org.springframework.beans.factory.

Config.propertyPlaceHolderConfigurer ">

/web-inf/jdbc.properties

[2]

Destroy-method = "close">

Name = "driverclassname"> $ {jdbc.driverclassname}

$ {jdbc.url}

$ {jdbc.username}

$ {jdbc.password}

[3]

Class = "Org.springframework.jdbc.datasource.dataasource">>

[4]

classpath: /sql-map-config.xml

[5]

Here's what the annotations mean:

[1] This bean handles the JDBC configuration. The JDBC configuration properties are in a standard JDBC configuration file, making them easier to maintain and read. Spring provides a configuring class that makes it easy to read property files without converting them to XML. [ 2] Here you see the data source. It's a standard J2EE data source. Many J2EE applications and frameworks hard-wire an application or framework to a given data source. Configuring them instead makes it easy to choose your own source (and thus your pooling STRATEGY).

[3] The applicationContext.xml configuration sets the transaction policy. This configuration specifies the implementation. This application uses the data source transaction manager, which delegates transaction management to the database via JDBC (using commit and rollback).

[4] The ibatis SQL MAP Utility for Building Dao Must Be Configured. It's done here.

.

This configuration accomplishes more than just decoupling the persistence tier from the model or the view. We've also decoupled transaction management from the persistence layer, separated the transaction policy from the implementation, and isolated the data source. Take a look at the broader benefits That has been gained beyond configuration.

Benefits

That's all of the persistence code for the Product. The code for the rest of jPetStore is similar. The application effectively isolates the entire domain model within a single layer. The domain has no dependencies on any services, including the data layer. You've Also Encapsulated All Data Access Into a Clean and Concise Dao Layer, Which Is Independent of Data Store. Notice What You don't See: Data Source Configuration

Handled by the Spring framework. You do not have to manage a whole bunch of singletons, for session management, data sources, and the like. You can also delay key decisions such as the type of data source until deployment time.

Connection Processing

The Spring framework manages all of the connection processing. One of the most common JDBC errors is a connection leak. If you're not very careful about closing your connections, especially within exception conditions, your application can easily lose stability and crash.

Specialized Exceptions

Many frameworks pass SQL exceptions to the top. They frequently have SQL codes built in that may be specialized to your own RDBMS, making it difficult to code portable applications. Spring has its own exception hierarchy, which insulates you from these issues. Further, should You change approaches to hibernate or jdo, you won't Need to change.

The end result of what we've done so far is pretty cool. We have a clean, transparent domain model and a low-maintenance service layer that's independent of our database. Each layer is neatly encapsulated. Now that we have looked at the backend Logic, It's Time to Put A User Interface ON this application.

PRESENTATION

In most places, the Spring framework does not reinvent working technologies. In the area of ​​presentation logic, though, Spring introduces a simple model-view-controller framework called MVC Web that has many competing architectures, like Struts and Java Server Faces (JSF .) Take solace, though you do not have to use MVC Web to use Spring But if you decide to do so, you will find a few advantages:... MVC Web does not dictate your choice of view Other frameworks tend to provide better support for favored view technologies, such as Velocity (proprietary) and Struts (JSP). for example, Struts exposes the model via request attributes. As a result, you need to build a bridge servlet to use a technology such as Velocity that doesn 't understand the Servlet API. Spring exposes the model through a generic map, so it can work with any view technology. MVC Web provides consistent configuration across all aspects of a Spring application. It uses the same inversion-of-control paradigm that the Other Fr AMEWORKS USE. MVC Web Makes Testing Easier. Since You Don't have to Extend Another Class (Like Action Or Actionform in Struts), You Can Easily Mock The Request and Response.

If you've ever used Struts, you're familiar with the basic paradigm of MVC Web. Figure 8-4 shows how it works. Controllers basically handle all incoming requests from input views. If the input request is a submitted form, the controller .

Figure 8-4. The MVC Web Framework Works Much Like Struts

CONFIGURATION

As with other elements of the Spring framework, when you're trying to understand a new application, start with the configuration files and drill down from there. In this example, the user interface is configured in the petstore-servlet.xml file.Consider HTML pages that search for products in a category, and search for products based on keywords. The configuration file needs two controllers to the application context file. Each entry specifies a controller and the model object, like in Example 8-10.

EXAMPLE 8-10. Excerpt from Web.xml

Class = "JPETSTORE.WEB.SPRING.SearchProductSController">

Recall that all access to our data layer goes through the façade. As you'd expect, these bean ID entries specify the façade, called petstore. Each form in the application works in the same way. Let's drill down further and look at the controller For searchproducts.

Controllers

For MVC Web, each form generally shares a single instance of a controller, which routes all requests related to a given form. It also marshals the form to the correct validation logic and returns the appropriate view to the user. Example 8-11 shows the Controller for the searchproducts view.

Example 8-11. SearchProductSController.java

Public Class searchProductScontroller imports controller {

[1] private petstorefacade petstore; public void setpetStore {

This.petStore = PetStore;

}

[2] Public ModilandView HandleRequest (httpservletRequest Request,

Httpservletresponse response

Throws exception {

[3] IF (Request.GetParameter ("Search")! = Null) {

String Keyword = Request.getParameter ("Keyword");

IF (keyword == null || keyword.length () == 0) {

Return New ModelandView ("Error",

"Message",

"Please enter a keyword to search for, the press the search button");

}

Else {

[4] PagedListholder ProductListList = New PagedListhold (

this.petstore.SearchProductList (Keyword.tolowerCase ())));

ProductList.SetPageSize (4);

Request.getSession () .SetaTRibute

"SearchProductScontroller_ProductList", ProductList);

[5] Return New ModelandView ("SearchProducts", "ProductList", ProductList);

}

}

Else {

[6] String Page = Request.getParameter ("Page");

PagedListholder ProductList = (PagedListholder) Request.getSession ().

GetaTtribute ("SearchProductScontroller_ProductList");

IF ("Next" .Equals (page)) {

ProductList.nextpage ();

}

Else IF ("previous" .equals (page) {

ProductList.Previouspage ();

}

Return New ModelandView ("SearchProducts", "ProductList", ProductList);

}

}

}

Here's what the annotations mean:

[1] Each Controller Has Access to the appropriate Domain Model. In this case, it's natural for the view to access the model..

[2] A controller has an interface like a servlet, but is not actually a servlet. User requests instead come in through a single dispatcher servlet, which routes them to the appropriate controller, populating the request membermeter. The controller merely responds to the ApproPriate Request, Invoking Business Data And Routing Control to the appropriate page. [3] in this case, The request is to "search" The Controller Must Parse Out the appropriate keywords.

[4] The Controller Invokes The Business Logic with the keywords provided by the user.

[5] The Controller Routes The Appropriate View Back to The User (with the appropriate model).

[6] in this case, the request is "page." ".". ".". ".". ".

Forms

.

Example 8-12. Accountform.java

Public class accountform {

PRIVATE ACCOUNT;

Private boolean newaccount;

PRIVATE STRING REPEATEDPASSWORD;

Public Accountform (Account Account) {

THIS.ACCOUNT = Account;

THIS.NEWACCOUNT = FALSE;

}

Public Accountform () {

This.account = New Account ();

THIS.NEWACCOUNT = TRUE;

}

Public Account getaccount () {

Return Accent;

}

Public boolean isnewaccount () {

Return newaccount;

}

Public void setrepeatedpassword (string repeatedpassword) {

This.RepeatedPassword = repeatedpassword;

}

Public string getrepeatedpassword () {

Return REPAATEDPASSWORD;

}

}

Each of these bean fields corresponds directly to an HTML input field or control. The Spring framework translates a submit request to the form, which can then be accessed as a POJO for validation, mapping input data, or other purposes. With Spring, unlike Struts Form Objects Can Be Any Java Bean. There's no need to extend Actionform. That's Important, Because You don't need to copy property from an actionform to a domain Object or value object.validation

You may have noticed validation logic within the original applciationContext.xml. These beans are generally considered business logic, but they've got a tight relationship to the user interface and they're invoked directly by the Spring framework. When a user submits a form Spring Fires The Validation Logic., Spring Routes Control to the appropriate page. EXAMPLE 8-13 Shows The AccountValidator Class, Which Validates The Account Form.

Example 8-13. AccountValidator.java

Public Class AccountValidator Implements VALIDATOR {

Public Boolean Supports (Class Clazz) {

Return Accent.class.IsassignableFrom (Clazz);

}

Public void validate (Object Obj, Errors Errors) {

ValidationUtils.rejectifeMpty (ErrorS, "Firstname", "first_name_required",

ValidationUtils.rejectife (ErrorS, "Lastname", "Last_Name_Required",

ValidationUtils.rejectifeMpty (Errors, "Email", "Email_Required",

ValidationUtils.rejectife (Errors, "Phone", "Phone_Required",

ValidationUtils.rejectife (Errors, "Address1", "Address_Required",

ValidationUtils.rejectifeMpty (Errors, "City", "City_Required",

ValidationUtils.rejectifeMpty (ErrorS, "State", "State_Required", ValidationUtils.rejectifeMpty (ErrorS, "Zip", "Zip_Required", "Zip is Required.");

ValidationUtils.rejectifeMpty (Errors, "Country", "Country_Required",

}

}

In this example, the Spring framework makes life easier for developers in several ways. The developer does not need to write validation methods by hand. Also, many prepackaged methods exist. The framework takes care of validation and routing. The framework takes care of routing Control based on selfcess or failure.

One chapter on the Spring framework can not do it justice, but you've seen the overall gist of it. The advantages of the framework-and more importantly, this coding style-should jump off the page at you if you have not seen it before. In particular, notice the clarity and simplicity that a cleanly layered architecture provides. You can probably imagine how easy it is to incorporate business logic with a transparent framework like Spring.

Summary

I've chosen the jPetStore application for a variety of reasons. The biggest is that you can quickly see the difference between a simple, fast, light application and the alternative. If you are not yet a believer, I challenge you to look up the .. EJB version of Pet Store If you've never seen it, you'll be blown away by the difference Our version is transparent and independent; the EJB example is invasive and dependent on the container Ours is easy to understand, whereas the. J2EE Counterpart Was Buried Under The Complexity of EJB BEST PRACTICES.

I have not always been a believer. In fact, I did not know who Rod Johnson was before we were introduced in Boston at a conference. I've since come to appreciate this simple framework as elegant and important. If you're New to Spring, You'Ve Seen Only A Single Application. I Hope That Through It, You Can See How IT Embraces The Principles in this book: Keep IT Simple

Spring's Easy To Use and understand. In A Single Chapter, Our Example Covers An Application With Transactions, Persistence, A Full Web Frontend, And A Completely Modular Configuration Engine.

Do One Thing, And Do IT Well

Spring's framework has many different aspects and subframeworks. However, it separates each concept nicely. The fundamental value of Spring is the bean factory and configuration service, which let you manage dependencies without coupling your code. Each additional layer of Spring is cleanly decoupled and independent .

Strive for transparency

Spring applications do not need to rely on the basic container at all. In fact, they can easily exist outside of the container. You need only create and configure them manually. This ability makes Spring applications a joy to test.

You are what you eat

Spring makes smart choices in the frameworks that it includes. The respected Apache projects for data sources and logging form a good foundation. Spring allows many configurable choices, letting you choose the best frameworks for a given solution.

Allow for Extension

.

I have not covered Spring in its entirety. My goal is only to show you that it's possible to build real-world applications that embrace the concepts set out in the first six chapters of this book. If you decide that you'd like to See More, Make Sure That You Look Into Spring's Advanced Features: Integration with Hibernate and JDO AOP Concepts Transactional Templates with JTA Support

The authors of Better, Faster, Lighter Java continue to explore practical examples of the principles of their book in other chapters. Pick up your copy to see, for example, an implementation of a service called Simple Spider, and see that service integrated into Spring You'll Be Able To See the Benefits of Improved Maintenance of a Framework Like this Going Forward.

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

New Post(0)