Transferred from: http://www.mamicode.com/info-detail-110033.html
After spring and hibernate are integrated, database operations through the Hibernate API are found to be opensession,close,begintransaction,commit every time, and these are repetitive tasks. We can hand over the transaction Management Section to the Spring framework.
Configure transactions (XML mode)
When you use spring to manage transactions, you no longer need to call BeginTransaction and commit in DAO, and you do not need to call Session.close (), using the API Sessionfactory.getcurrentsession () to replace sessionfactory.opensession ()
1 @Repository 2 public class Userdaoimpl implements Userdao {3 @Autowired 4 private Sessionfactory sessionfactory ; 5 6 Public User Finduserbyid (int id) {7 session session = Sessionfactory.getcurrentsession (); 8 User user = (user) Session.get (user.class, id); 9 session.delete (user), return user;12 }13}
Sessions created with getcurrentsession () are bound to the current thread, while the session created with Opensession () does not.
Sessions created with Getcurrentsession () are automatically closed on commit or rollback, and the session created with Opensession () must be closed manually.
Use Getcurrentsession () to include the following configuration in the Hibernate.cfg.xml file:
* If you are using a local transaction (JDBC Transaction)
<property name= "Hibernate.current_session_context_class" >thread</property>
* If you are using a global transaction (JTA Transaction)
<property name= "Hibernate.current_session_context_class" >jta</property>
If the Hibernate4 is used, the transaction must be configured with Getcurrentsession (), otherwise it cannot be taken to the session
Applicationcontext.xml Configuration
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans 3 xmlns= "Http://www.springframework.org/schema/beans" 4 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p= "http://www.springframework.org/schema/p" 6 xmln s:context= "Http://www.springframework.org/schema/context" 7 xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "8 xmlns:tx=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX "9 xmlns:jpa=" http://www.springframework.org/schema/data/jp A "ten xmlns:cache=" Http://www.springframework.org/schema/cache "one xsi:schemalocation="/http Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd12 Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd13 HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/sche Ma/aop/spring-aop-3.0.xsd14 Http://www.springframewoRK.ORG/SCHEMA/DATA/JPA http://www.springframework.org/schema/data/jpa/spring-jpa.xsd15 http://www. Springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd16 http://www. Springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd ">17 <conte Xt:component-scan base-package= "DAO"/>19 <context:component-scan base-package= "service"/>20 <context:c Omponent-scan base-package= "Test"/>21 <context:property-placeholder location= "Classpath:dbcp.properties"/ >23 <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >24 & Lt;property name= "Driverclassname" value= "${driverclassname}"/>25 <property name= "url" value= "${url}"/> <property name= "username" value= "${mysqlusername}"/>27 <property name= "password" value= "${mys Qlpassword} "/>28 <property name= "maxactive" value= "${maxactive}"/>29 <property name= "Maxidle" value= "${maxIdle}"/> ; <property name= "Minidle" value= "${minidle}"/>31 <property name= "maxwait" value= "${maxWait}" />32 <property name= "initialsize" value= "${initialsize}"/>33 <property name= "logAbandoned" va Lue= "${logabandoned}"/>34 <property name= "removeabandoned" value= "${removeabandoned}"/>35 <p Roperty name= "Removeabandonedtimeout" value= "${removeabandonedtimeout}"/>36 <property name= "TimeBetweenEvic Tionrunsmillis "value=" ${timebetweenevictionrunsmillis} "/>37 <property name=" NumTestsPerEvictionRun "value= "${numtestsperevictionrun}"/>38 </bean>39 <bean id= "sessionfactory" class= "org.springframework . Orm.hibernate4.LocalSessionFactoryBean ">41 <property name=" DataSource "ref=" DataSource "/>42 43 <property NamE= "Hibernateproperties" >44 <props>45 <prop key= "Hibernate.dialect" >org.hibernat e.dialect.mysqldialect</prop>46 <prop key= "Hibernate.show_sql" >true</prop>47 <prop key= "Current_session_context_class" >thread</prop>48 </props>49 </prope Rty>50 Wuyi <property name= "Packagestoscan" >52 <list>53 <value >po</value>54 </list>55 </property>56 </bean>57 <!--hi Bernate4 must be configured to turn on the transaction otherwise getcurrentsession () is not getting <bean id= "Txmanager" class= " Org.springframework.orm.hibernate4.HibernateTransactionManager ">61 <property name=" sessionfactory "ref=" ses Sionfactory "></property> </bean>63 <tx:advice id=" Txadvice "transaction-manager=" Txma Nager ">65 <tx:attributes>66 ≪tx:method name= "find*" propagation= "REQUIRED"/>67 <tx:method name= "*" read-only= "true"/>68 </tx:attributes>69 </tx:advice>70 <aop:config proxy-target-class= "true" >72 < !--<aop:advisor advice-ref= "Txadvice" pointcut= "Execution (* dao.*.* (..))" />-->73 <aop:pointcut expression= "Execution (* dao.*.* (..))" id= "Pointcut"/>74 <aop:advisor advice-ref= "Txadvice" pointcut-ref= "pointcut"/>75 </aop:config>76 </beans>
A detailed description of the transaction properties of the propagation class in spring:
Propagation_required: Supports the current transaction and creates a new transaction if there is no current transaction. This is the most common choice.
Propagation_supports: Supports the current transaction and is executed in a non-transactional manner if no transaction is currently in use.
Propagation_mandatory: Supports the current transaction and throws an exception if there is no current transaction.
Propagation_requires_new: Creates a new transaction and suspends the current transaction if a transaction is currently present.
Propagation_not_supported: Executes the operation in a non-transactional manner, suspending the current transaction if a transaction is currently present.
Propagation_never: Executes in a non-transactional manner and throws an exception if a transaction is currently present.
Propagation_nested: Supports the current transaction, executes a nested transaction if the current transaction exists, and creates a new transaction if there is no current transaction.
Configuring Transactions (declarative)
Needs to be set in XML formulation <tx:annotation-driven transaction-manager="TransactionManager">
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans 3 xmlns= "Http://www.springframework.org/schema/beans" 4 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p= "http://www.springframework.org/schema/p" 6 xmln s:context= "Http://www.springframework.org/schema/context" 7 xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "8 xmlns:tx=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX "9 xmlns:jpa=" http://www.springframework.org/schema/data/jp A "ten xmlns:cache=" Http://www.springframework.org/schema/cache "one xsi:schemalocation="/http Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd12 Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd13 HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/sche Ma/aop/spring-aop-3.0.xsd14 Http://www.springframewoRK.ORG/SCHEMA/DATA/JPA http://www.springframework.org/schema/data/jpa/spring-jpa.xsd15 http://www. Springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd16 http://www. Springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd ">17 <conte Xt:component-scan base-package= "DAO"/>19 <context:component-scan base-package= "service"/>20 <context:c Omponent-scan base-package= "Test"/>21 <context:property-placeholder location= "Classpath:dbcp.properties"/ >23 <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >24 & Lt;property name= "Driverclassname" value= "${driverclassname}"/>25 <property name= "url" value= "${url}"/> <property name= "username" value= "${mysqlusername}"/>27 <property name= "password" value= "${mys Qlpassword} "/>28 <property name= "maxactive" value= "${maxactive}"/>29 <property name= "Maxidle" value= "${maxIdle}"/> ; <property name= "Minidle" value= "${minidle}"/>31 <property name= "maxwait" value= "${maxWait}" />32 <property name= "initialsize" value= "${initialsize}"/>33 <property name= "logAbandoned" va Lue= "${logabandoned}"/>34 <property name= "removeabandoned" value= "${removeabandoned}"/>35 <p Roperty name= "Removeabandonedtimeout" value= "${removeabandonedtimeout}"/>36 <property name= "TimeBetweenEvic Tionrunsmillis "value=" ${timebetweenevictionrunsmillis} "/>37 <property name=" NumTestsPerEvictionRun "value= "${numtestsperevictionrun}"/>38 </bean>39 <bean id= "sessionfactory" class= "org.springframework . Orm.hibernate4.LocalSessionFactoryBean ">41 <property name=" DataSource "ref=" DataSource "/>42 43 <property NamE= "Hibernateproperties" >44 <props>45 <prop key= "Hibernate.dialect" >org.hibernat e.dialect.mysqldialect</prop>46 <prop key= "Hibernate.show_sql" >true</prop>47 <prop key= "Current_session_context_class" >thread</prop>48 </props>49 </prope Rty>50 Wuyi <property name= "Packagestoscan" >52 <list>53 <value >po</value>54 </list>55 </property>56 </bean>57 <bean Id= "Txmanager" class= "Org.springframework.orm.hibernate4.HibernateTransactionManager" >60 <property name= "se Ssionfactory "ref=" sessionfactory "></property> </bean>62 <tx:annotation-driven transaction-m Anager= "Txmanager"/>63 </beans>
How to annotate things: @Transactional
When marked in front of a class, all methods in the indicated class are processed, and the following code is transacted at the service layer (configuring transactions to the service layer is a good way, because a service layer method operation can be associated to multiple DAO operations.) These DAO operations are performed at the service layer, and many DAO operations have failed all rollbacks, and the success is all committed. )
1 @Service 2 @Transactional 3 public class Userserviceimpl implements UserService {4 @Autowired 5 Private Userdao Userdao; 6 7 public User Getuserbyid (int id) {8 return Userdao.finduserbyid (ID); 9 }10}
When certain methods in a class do not require things:
1 @Service 2 @Transactional 3 public class Userserviceimpl implements UserService {4 @Autowired 5 Private Userdao Userdao; 6 7 @Transactional (propagation = propagation.not_supported) 8 public User Getuserbyid (int id) {9 return Userdao.finduserbyid (ID); }11}
@Transactional (propagation=propagation.required)
If there is a transaction, then join the transaction and create a new one (by default)
@Transactional (propagation=propagation.not_supported)
Container does not open transactions for this method
@Transactional (propagation=propagation.requires_new)
Creates a new transaction regardless of whether a transaction exists, the original hangs, the new execution completes, and the old transaction continues
@Transactional (Propagation=propagation.mandatory)
Must be executed in an existing transaction, or throw an exception
@Transactional (Propagation=propagation.never)
Must be executed in a non-transaction, otherwise throws an exception (as opposed to propagation.mandatory)
@Transactional (Propagation=propagation.supports)
If the other bean calls this method and declares the transaction in another bean, the transaction is used. If the other bean does not declare the transaction, then there is no transaction.
Things timeout settings:
@Transactional (timeout=30)//default is 30 seconds
Transaction ISOLATION Level:
@Transactional (isolation = isolation.read_uncommitted)
READ UNCOMMITTED data (dirty read, non-repeatable read) basic not used
@Transactional (isolation = isolation.read_committed)
Read committed data (non-repeatable read and Phantom reads occur)
@Transactional (isolation = isolation.repeatable_read)
REPEATABLE READ (phantom read occurs)
@Transactional (isolation = isolation.serializable)
Serialization
MYSQL: Default to Repeatable_read level
SQL Server: Default is read_committed
Dirty reads : One transaction reads uncommitted update data to another transaction
non-repeatable read : In the same transaction, multiple reads of the same data are returned with different results, in other words,
Subsequent reads can be read to the updated data submitted by another transaction. Conversely, "repeatable reads" are repeated in the same transaction
When reading data, it is guaranteed to read the same data, that is, subsequent reads cannot be read to another transaction committed update data
Phantom reads : One transaction reads the insert data that has been committed by another transaction
Spring Consolidation Hibernate4: Transaction management