Why use spring to manage hibernate?

Source: Internet
Author: User

Why use the Hibernate framework? This is already mentioned in the hibernate introduction blog.

Since the Hibernate framework is used to access and manage the persistent layer, why does spring be used to manage and integrate hibernate?

First, let's take a look at the hibernate operation steps. For example, add a user. In the previous blog, "Step 8 describes how to build and use hibernate" details the steps for using hibernate. The following code is from the previous blog. Here, we only provide one explanation for the question. If you want to see the complete code example, you can refer to "eight steps to explain how to build and use hibernate".

You can see that the hibernate operation steps are as follows:

1.
Get configuration object

2.
Create sessionfactory

3.
Create a session

4.
Open transaction

5.
For persistence. For example, the above user adding operation

6.
Commit transactions

7.
An exception occurred. roll back the transaction.

8.
Close transactions

Use hibernate to access the persistent layer. These eight steps are required each time. But what if I use spring to manage hibernate?

First, Spring provides the hibernatetemple class for hibernate. This template class encapsulates sessions. By default, spring automatically submits transactions. Directly write this. Save (object) to the DaO layer.

 

In practice, I encountered a problem and was unable to insert the database. After some painstaking efforts, I tried and verified it multiple times. I summarized the cause and the results are as follows:

Note: All operations must be performed in the transaction. If you simply use hibernate, You need to manually enable the commit operation to close the transaction. Of course, it can also be automatically submitted in the hibernate configuration file.

If you use spring to manage hibernate, the default transaction is automatically committed. However, note that if you use spring to configure the data source in the configuration file instead of hibernate. cfg. XML, the database can be inserted successfully, because hibernatetemple provides automatic transaction submission by default. The configuration file in spring configures the data source as follows: jar required to use this data source is as follows: commons-dbcp.jar, commons-pool.jar, msbase. jar, MSSQLServer. jar,
Msutil. jar, sqljdbc4.jar;

<Bean id = "datasource" class = "org. apache. commons. DBCP. basicdatasource "> <property name =" driverclassname "value =" com. microsoft. JDBC. sqlserver. sqlserverdriver "> </property> <property name =" url "value =" JDBC: sqlserver: // 192.168.24.176: 1433; database = test "> </property> <property name =" username "value =" sa "> </property> <property name =" password "value =" 123 "> </property> </bean> <bean id = "sessionfactory" class = "org. SP Ringframework. Orm. hibernate3.localsessionfactorybean "> <property name =" datasource "ref =" datasource "> </property> <! -- Hibernate property configuration --> <property name = "hibernateproperties"> <props> <prop key = "hibernate. dialect "> Org. hibernate. dialect. sqlserverdialect </prop> <prop key = "hibernate. hbm2ddl. auto "> Update </prop> </props> </property> <! -- If the traditional HBM is used. you can use the following XML method to simplify HBM registration. and the class is localsessionfactorybean --> <property name = "mappinglocations"> <list> <value> classpath: user. HBM. XML </value> </List> </property> </bean>

If spring does not directly configure the data source, it uses hibernate. cfg. XML, you cannot directly this. save (object), you cannot insert it into the database, but it can be saved in the cache. Because all the operations are performed in the transaction, and the hibernate. cfg. XML data source is automatically submitted by default. The solution is as follows: You can enter it in hibernate. cfg. xml:

<Property name = "hibernate. Connection. autocommit"> true </property>

The following spring uses the hibernate. cfg. XML Data Source

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property><property name="mappingLocations"><list><value>classpath:User.hbm.xml</value></list></property></bean> 

The above introduces the advantages of spring to manage hibernate. You do not need to manually create sessionfactory or session, or manually start or commit to close the transaction. All of this is managed by spring. Spring also provides the hibernatetemple tool to make all operations simple and convenient.

The Dao layer is configured in the spring configuration file as follows:

<bean id="userDao" class="com.UserDao.UserDaoImpl"><property name="sessionFactory" ref="sessionFactory"></property></bean>

The code at the DaO layer is as follows:

package com.UserDao;import org.springframework.orm.hibernate3.HibernateTemplate;import com.user.User;public class UserDaoImpl extends HibernateTemplate implements UserDao {@Overridepublic void insert(User user) {this.save(user);}}

This is only the key code. The complete demo has been uploaded.
 

As mentioned above, all operations are in the transaction. The transaction concept must be familiar to everyone. In general, transactions should be applied at the business logic layer rather than the DaO layer. In addition, spring has a good encapsulation of transactions. It has a set of encapsulation of transaction management, which separates the business logic from the transaction management to further achieve decoupling. In the next blog, we will continue to explain how spring manages transactions in hibernate.

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.