When Hibernate encounters Spring

Source: Internet
Author: User

Author: Naveen Balani from: IBM

In the previous phase of this series, I introduced seven modules of the Spring framework, including Spring AOP and IOC containers. Then I used a simple example to demonstrate how the IOC mode (implemented by the Spring IOC container) integrates distributed systems in a loosely coupled manner.

Now, from where I ended last time, I used a similar example to demonstrate declarative transaction processing supported by Spring AOP and Spring Hibernate, so I started with an in-depth study of these two technologies.

  Spring AOP

A software system usually consists of multiple components, each of which is responsible for a specific functional area. However, these components often take extra responsibilities beyond their core functions. System services (such as logs, transaction management, and security) often find themselves in the field of other components, and the core responsibilities of these components are other things. The result is the so-called "code tangle", or simply "a mess ". Aspect-oriented programming is a programming technique that attempts to solve this problem. It promotes the isolation of concerns to the core programming concept.

When using AOP, the public functions of the system are still defined in one place, but it can be declared to define how and where to apply this function. If you modularize the cross-cutting concerns (such as log and transaction management), you can add new features to the code without modifying each individual class. This type of modularization focuses on aspects.
 
Take an enterprise application as an example. Such applications generally require services similar to security and transaction support. Obviously, the support of these services can be directly written into every class of the required service, but it is also expected that the same transaction processing code is not required for a large number of transactional contexts. If Spring AOP is used for transaction processing, you can schedule appropriate method calls in a declarative manner without having to schedule them one by one.

Spring AOP provides several aspects to declare transactions for JavaBean. For example, TransactionProxyFactoryBean is a convenient proxy class that can intercept method calls to existing classes and apply the transaction context to the transaction bean. The following example shows the actual application of this class.

  Hibernate

The Spring framework provides integration support for hibernate, JDO, and ibatis SQL maps. Spring supports hibernate at the first level. It integrates many convenient features of IOC and solves many typical hibernate integration problems. The Framework's support for hibernate conforms to spring's general transaction and Data Access Object (DAO) exception hierarchies.

Spring provides support for using the selected or ing layer to create data access applications. Because everything is designed as a set of reusable JavaBean, No matter what technology you choose, you can access the or ing support of most spring in the library format. The advantages of or ing inside applicationcontext or beanfactory are that it simplifies configuration and deployment.

Hibernate is a fully functional, open-source or ing framework on the Java platform. Hibernate supports developing persistent classes that conform to the conventional Java philosophy-including Association, inheritance, polymorphism, composition, and Java Collection frameworks. The Hibernate query language (hql) is designed as a micro-object-oriented extension of SQL, which serves as a bridge between objects and the relational world. Hibernate also supports expressing queries using raw SQL or Java-based standard and sample queries. Hibernate uses the XML (*. HBM. XML) file to map Java classes to tables and JavaBean attributes to database tables.

Supports all SQL database management systems through JDBC technology. Hibernate is well integrated with all popular J2EE application servers and web containers.

  Actual Example

A bank application example allows you to see how well Spring AOP and hibernate work together. The bank account use case allows a user (customer) to open one or more bank accounts in a transaction. You can apply for multiple bank accounts. You can select a check account or a savings account.

Application database (cloudscape ?) Contains all customer and account information. In this example, we assume that there is a 1: n association between the customer and the account class. In real-life scenarios, association may need to be modeled by M: n to support joint accounts.

Because you must be able to apply for multiple accounts in a transaction, you must first implement a DOA mode for database interaction. Then configure the transactionproxyfactorybean of Spring AOP to intercept method calls and apply the transaction context to the DOA declarative.

  Hibernate practices

In the Spring framework, resources such as JDBC datasource or hibernate sessionfactory can be implemented using bean in the application context. Application objects that need to access resources only need to get the reference of such pre-defined instances through bean reference (more about this in the next section ). In listing 1, you can see an excerpt from the sample bank application: the XML application context definition shows how to set the JDBC datasource and put a hibernate sessionfactory on it.

Listing 1. JDBC datasource and hibernatesessionfactory connection

<! -- Datasource Property -->
<Bean id = "exampledatasource"
Class = "org. Apache. commons. DBCP. basicdatasource">
<Property name = "driverclassname">
<Value> org. Apache. Derby. JDBC. embeddeddriver </value>
</Property>
<Property name = "url">
<Value> jdbc: derby: springexample; create = true </value>
</Property>
</Bean>

<! -- Database Property -->
<Bean id = "exampleHibernateProperties"
Class = "org. springframework. beans. factory. config. PropertiesFactoryBean">
<Property name = "properties">
<Props>
<Prop key = "hibernate. hbm2ddl. auto"> update </prop>
<Prop
Key = "hibernate. dialect"> net. sf. hibernate. dialect. DerbyDialect </prop>
<Prop
Key = "hibernate. query. substitutions"> true 'T', false 'F' </prop>
<Prop key = "hibernate. show_ SQL"> false </prop>
<Prop key = "hibernate. c3p0. minPoolSize"> 5 </prop>
<Prop key = "hibernate. c3p0. maxPoolSize"> 20 </prop>
<Prop key = "hibernate. c3p0. timeout"> 600 </prop>
<Prop key = "hibernate. c3p0. max_statement"> 50 </prop>
<Prop
Key = "hibernate. c3p0. testConnectionOnCheckout"> false </prop>
</Props>
</Property>
</Bean>

<! -- Hibernate SessionFactory -->
<Bean id = "exampleSessionFactory"
Class = "org. springframework. orm. hibernate. LocalSessionFactoryBean">
<Property name = "dataSource">
<Ref local = "exampleDataSource"/>
</Property>
<Property name = "hibernateproperties">
<Ref bean = "examplehibernateproperties"/>
</Property>
<! -- Or Mapping Files. -->
<Property name = "mappingresources">
<List>
<Value> customer. HBM. xml </value>
<Value> account. HBM. xml </value>
</List>
</Property>
</Bean>

Listing 1 shows how to configure the data source Bean (exampledatasource) for the sample application database (cloudscape ). Exampledatasource is connected to sessionfactory of spring hibernate. Note that *. HBM. xml specifies the or ing file of the sample application.

After the data source and session factory are set, the next step is to connect in DAO. In the CustomerDAOImpl example, SessionFactory is used. Next, insert Spring's TransactionProxyFactoryBean, which will intercept the method call to the CustomerDAOImpl object of the application and apply the transaction on it in a declarative manner.

Listing 2. Write the application DAO and TransactionManager together

<! -- Pass the session factory to our CustomerDAO -->
<Bean id = "mermerdaotarget"
Class = "springexample. hibernate. CustomerDAOImpl">
<Property name = "sessionFactory"> <ref local = "exampleSessionFactory"/>
</Property>
</Bean>

<Bean id = "transactionManager"
Class = "org. springframework. orm. hibernate. HibernateTransactionManager">
<Property name = "sessionFactory">
<Ref bean = "exampleSessionFactory"/>
</Property>
</Bean>

<Bean id = "userDAO"
Class = "org. springframework. transaction. interceptor. TransactionProxyFactoryBean">
<Property name = "transactionManager"> <ref local = "transactionManager"/>
</Property>
<Property name = "target"> <ref local = "customerDAOTarget"/>
</Property>
<Property name = "transactionAttributes">
<Props>
<Prop key = "addCustomer"> PROPAGATION_REQUIRED </prop>
</Props>
</Property>
</Bean>

In this example in Listing 2, The addCustomer method of the CustomerDAOImpl class is executed as a part of the transaction and has a transaction attribute PROPAGATION_REQUIRED. This attribute is equivalent to TX_REQUIRED Of The EJB container. If you want to keep this method running in a transaction, you can use PROPAGATION_REQUIRED. If the transaction is already running, the bean method is added to the transaction. Otherwise, the lightweight Transaction Manager of Spring starts a transaction. If you want to always start a new transaction when calling the component service, you can use the PROPAGATION_REQUIRES_NEW attribute.

After the application connection is complete, you can view the source code further.

  Analyze this!

If you haven't done this before, download the source code of this article. Release the source zip file to any location on the computer, such as c :/. Creates a folder named SpringProjectPart2. The src/spring folder contains the Hibernate ing file and Spring configuration file of the sample application. The src/springexample/hibernate file contains the source code of the application.

Here we will find two classes, Customer and Account, which are mapped to two tables using the Hibernate ing file. The Customer class represents the Customer information, and the Account represents the Customer's Account information. As mentioned above, I have modeled these two classes according to the 1: N relationship, that is, a Customer can have multiple accounts. Listing 3 shows the Hibernate ing file of the Customer object.

Listing 3. Hibernate ing file of the Customer object

<? Xml version = "1.0"?>

<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 2.0 // EN"
Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>

<Hibernate-mapping>
<Class
Name = "springexample. hibernate. Customer"
Table = "TBL_CUSTOMER"
Dynamic-update = "false"
Dynamic-insert = "false">

<Id
Name = "id"
Column = "CUSTOMER_ID"
Type = "java. lang. Long"
Unsaved-value = "-1"
>
<Generator class = "native">
</Generator>
</ID>

<Set name = "accounts"
Inverse = "true"
Cascade = "all-delete-Orphan">
<Key column = "customer_id"/>
<One-to-learn class = "springexample. hibernate. Account"/>

</Set>

<Property
Name = "email"
Type = "string"
Update = "false"
Insert = "true"
Column = "CUSTOMER_EMAIL"
Length = "82"
Not-null = "true"
/>

<Property
Name = "password"
Type = "string"
Update = "false"
Insert = "true"
Column = "CUSTOMER_PASSWORD"
Length = "10"
Not-null = "true"
/>

<Property
Name = "userId"
Type = "string"
Update = "false"
Insert = "true"
Column = "CUSTOMER_USERID"
Length = "12"
Not-null = "true"
Unique = "true"
/>

<Property
Name = "firstName"
Type = "string"
Update = "false"
Insert = "true"
Column = "CUSTOMER_FIRSTNAME"
Length = "25"
Not-null = "true"
/>

<Property
Name = "lastName"
Type = "string"
Update = "false"
Insert = "true"
Column = "customer_lasttname"
Length = "25"
Not-null = "true"
/>

</Class>

</Hibernate-mapping>

Set Name = "accounts" and a pair of multi-class labels specify the relationship between the customer and the account. I also defined the account object ing in the account. HBM. xml file.

Customerdaoimpl. Java represents the DAO of the application. It inserts client and account information into the application database. Customerdaoimpl extends spring's hibernatedaosupport, which simplifies session management with spring hibernatetemplate. In this way, you can use the gethibernatetemplate () method to save or retrieve data. The getmermeraccountinfo () shown in the following figure finds the customer and obtains the customer's account information through the gethibernatetemplate (). Find method using hql, as shown in Listing 4.

Listing 4. DAO implementation

Public class CustomerDAOImpl extends HibernateDaoSupport
Implements CustomerDAO {

Public void addCustomer (Customer customer ){
GetHibernateTemplate (). save (customer );
// TODO Auto-generated method stub

}

Public Customer getCustomerAccountInfo (Customer customer Customer ){
Customer cust = null;
List list = getHibernateTemplate (). find ("from Customer customer" +
"Where customer. userId =? ",
Customer. getUserId (), Hibernate. STRING );

If (list. size ()> 0 ){
Cust = (Customer) list. get (0 );
}

Return cust;

}

All of these should be easy to grasp. Now let's look at the actual application of the code!

  Run the application

To run the sample application, you must first download the Spring framework and all its dependent files. Next, release the framework to a location such as c:/, which creates the folder C:/spring-framework-1.2-rc2 for the current release ). You must download and release Apache Ant and Cloudscape before continuing. After downloading Cloudscape, release it to c:/, which creates the C:/Cloudscape_10.0 folder.

Next, release the source code to c:/, which will create the SpringProject2 folder. Next, modify the build. xml file portal, replace the C:/spring-framework-1.2-rc2 with the actual installation location of Cloudscape instead of C:/Program Files/IBM/Cloudscape_10.0.

Open the command line prompt, enter the SpringProject directory, and enter the following command at the command line prompt: build.

This constructs and runs the CreateBankCustomerClient class. It creates a Customer Class Object, fills it with data, creates an Account object, fills it with data, and adds it to the Customer object.

Then CreateBankCustomerClient will call the CustomerDAOImpl. addCustomer class to add the customer and account information. Once the insertion is complete, CreateBankCustomerClient calls the CustomerDAOImpl. getCustomerAccountInfo method to obtain the customer and account information based on the userid. If CreateBankCustomerClient is successfully executed, the user ID is printed on the console. You can also query the Cloudscape database to retrieve the customer and account information.

  Conclusion

In part 2 of the three Spring series, I introduced how to integrate Spring Hibernate and Spring AOP. The result is a strong persistence framework that supports declarative transactions.

In the next and last articles in this series, I will introduce Spring's MVC module and how to use it to simplify Web-based application creation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.