Comments
litl_phil wrote: While it's nice that Google and Acer share the vision of cloud-based computing, it's also worth noting that we at litl already have a webbook on the market (available at litl.com) that runs our own cloud-based OS. Unlike Chrome, litlOS is focused on creating a new and better web experience for the home, so we don't have the usual browser interface, we have our own innovative UI. In conjunction with easel mode (litl's inverted-V position) and our growing cohort of litl channels (special apps t...
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Java Feature — Using the Java Persistence API (JPA) with Spring 2.0
How to use JPA in new or existing Spring applications to achieve standardized persistence

The persistence unit name is just the name of the persistence unit, and the data source is defined in the usual way. Spring always uses one or more Java 2 Standard Edition (J2SE) data source definitions as the starting point for persistence configuration. A number of data source types are available, but in this case we're using a simple pooled JDBC data source defined as follows:

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
       <property name="url" value="jdbc:oracle:thin:@booksvr.org:1521:BOOKS"/>
       <property name="userName" value="scott"/>
       <property name="password" value="tiger"/>
    </bean>

The loadTimeWeaver property specifies the weaving strategy that Spring uses to implement the container provider SPI and provides the weaving capability. In this example we use the instrumentation feature introduced in the Java SE 5 VM (specified on the jre command line) so we specify the InstrumentationLoadTimeWeaver class. If we were running in a Tomcat server, we would set this to ReflectiveLoadTimeWeaver and use the Tomcat class loader provided by Spring. If we were running Spring inside the Oracle Containers for J2EE (OC4J) server, we would set it to OC4JLoadTimeWeaver, which plugs into the special class-loading support in OC4J.

Configuring the Vendor Adapter
A keen observer might have noticed that we snuck an additional fourth dependency into the entity manager factory bean and wired it to a bean called vendorAdapter. The jpaVendorAdapter property is an optional property that facilitates setting vendor-specific properties that are common across providers. These properties detail:

  • Whether the SQL traces should be logged
  • The database platform that's being used
  • Whether the schema should be generated in the database when the application starts
We added this property because the various persistence providers tend to provide a mechanism for configuring these properties, but the mechanisms differ from provider to provider. By defining common property names in Spring, the settings can be specified regardless of the provider implementation being wired in underneath. This facilitates switching between different persistence providers by minimizing configuration changes - something that can help users determine which of the available providers exhibits the best performance or can best meet their application requirements.

The following is the definition of the vendorAdapter bean that we wired to the jpaVendorAdapter property. It defines TopLink as the vendor and gives values to the three common property settings.

    <bean id="vendorAdapter" class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
       <property name="databasePlatform" value="${platform}"/>
       <property name="showSql" value="true"/>
       <property name="generateDdl" value="true"/>
    </bean>

The databasePlatform string is understood by the persistence provider so even though the property name is common, the values may be different across vendors. We have assigned it the variable platform and defined it in an external application context properties file. (See Professional Java Development with the Spring Framework for a description of how to define and use properties files.).

Implementations such as TopLink define many more JPA settings that can be used to configure the provider in ways ranging from specifying what kind of cache to use to declaring custom classes and mapping types. These additional properties are typically defined as properties in the persistence.xml file.

Other Configurations
The next thing we need to do is declare the BookInventorySystem class as a Spring bean. The simple bean definition merely points out that Spring should proxy and manage instances of the class as they are created.

    <bean class="org.bookguru.BookInventorySystem"/>

Next, we'll use the local resource-level transactions provided by the JPA entity manager, so we define the transaction manager bean and bind it to the JpaTransactionManager class. We then refer its entity manager factory dependency to our entity manager factory bean.

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
       <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

This transaction manager is designed to support transactional connections through JPA but it will also allow direct JDBC access using Spring's JDBC abstraction library.

We need to do a bit of housekeeping to indicate to Spring that it should honor and act on any @PersistenceContext and @Transactional annotations found in bean classes. This is done by adding the following two simple elements:

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
    <tx:annotation-driven/>

The tx namespace and schema should be added to the top of the application context XML file so the namespace can be recognized.

Testing
Spring is designed to facilitate agile development practices - particularly to make testing much easier than in traditional Java EE development. The use of dependency injection and POJO programming makes unit testing much easier in general, but Spring doesn't stop there.

Spring provides a powerful integration test facility that lets code that accesses persistent data be tested without deploying to an application server or any container other than Spring. This functionality is packaged in the spring-mock.jar file included in the Spring distribution and provides the following services:

  • Automatic transaction demarcation. Each test runs in its own transaction, which is rolled back by default. This ensures that each test can run in its own sandbox without producing side effects.
  • Caching configurations. A configuration such as the O-R mappings is loaded only once, ensuring that start-up costs aren't repeated for each and every test.
  • Dependency injection of test cases. Test cases can be injected just like application components, making them easier to develop and initialize.
Taken together, these services mean that tests can be written quickly and easily, and executed in seconds. The following example shows how easily we can test our book inventory system.
About Mike Keith
Mike Keith has more than 15 years of teaching, research and practical experience in object-oriented and distributed systems, specializing in object persistence. He was the co-specification lead for EJB 3.0 (JSR 220), a member of the Java EE 5 expert group (JSR 244) and co-authored the premier JPA reference book Pro EJB 3: Java Persistence API. Mike is currently a persistence architect for Oracle and a popular speaker at numerous conferences and events around the world.

About Rod Johnson
Rod Johnson is the CEO of Interface21 and an authority on Java and J2EE development. He is a best-selling author, experienced consultant, and open source developer, as well as a popular conference speaker. Rod is the founder of the Spring Framework, which began from code published with Expert One-on-One J2EE Design and Development.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Very disappointing. I though Rod Johnson would have done much better than this.
There is no link to download a working example plus there is at least one error. The bean definition below, which is included in the article, violates the schema definition because the attribute class cannot be defined in a property element. :(

http://java.sys-con.com/read/36

In regards this point:
>>
The Java Persistence API was architected so it could be used both inside and outside a Java EE 5 container. When there's no container to manage JPA entity managers and transactions, the application must bear more of the management burden.
<<
Is there any plan to have JPA provide a "Stateless" or "Sessionless" architecture - where there would be no requirement to manage EntityManager's?

(and would make using JPA outside a container much simpler)


Your Feedback
GIUSEPPE SCHIAVO wrote: Very disappointing. I though Rod Johnson would have done much better than this. There is no link to download a working example plus there is at least one error. The bean definition below, which is included in the article, violates the schema definition because the attribute class cannot be defined in a property element. :( http://java.sys-con.com/read/36
Rob Bygrave wrote: In regards this point: >> The Java Persistence API was architected so it could be used both inside and outside a Java EE 5 container. When there's no container to manage JPA entity managers and transactions, the application must bear more of the management burden. << Is there any plan to have JPA provide a "Stateless" or "Sessionless" architecture - where there would be no requirement to manage EntityManager's? (and would make using JPA outside a container much simpler)
Enterprise Open Source Magazine Latest Stories . . .
Oracle seems to have divided the open source ranks over the MySQL delay it’s having closing its acquisition of Sun. Eben Moglin, the GPL’s most ardent defender and delineator, the lawyer who has worked hand in glove for years with the Free Software Foundation’s founder Richard Stallman...
Cloud computing is a game changer. The cloud is disrupting traditional software and hardware business models by disrupting how IT service gets delivered. Entrepreneurial opportunities abound as this classic disruptive technology begins to proliferate, so it is no surprise that SYS-CON'...
The irony is that Oracle has advanced MySQL, lost money in the process, and helped its competitors - all at the same time. When Oracle buys Sun and controls MySQL the gift (other than to Microsoft SQL Server) keeps on giving as the existential threat to RDBs is managed by Redwood Shore...
WSO2, the open source SOA company, today announced the launch of the WSO2 Cloud Platform. Available today, the new WSO2 Cloud Platform features a family of WSO2 Cloud Virtual Machines; WSO2 Cloud Connectors for enabling fast, secure cloud services; and the multi-tenant WSO2 Governance-...
Now, the open source Mozilla Thunderbird client software can be used with Open-Xchange collaboration software. The "Community OXtender for Thunderbird" software connector gives users full access to appointments and contacts stored in the Open-Xchange Server and enables them to use Thun...
Morph Labs, a leading provider of enterprise cloud computing technology, today announced an introductory trial of the Morph CloudServer, an open, standards-based server IT organizations can use to rapidly model and evaluate their cloud implementations. A miniature "Cloud Environment in...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE