search
HomeJavajavaTutorialDetailed code explanation of Spring and Hibernate for Java transaction management learning

This article mainly introduces you to the relevant information of Spring and Hibernate for learning Java transaction management. The article introduces it in detail through sample code. Friends who need it can refer to it. Let's take a look together.

Environment and version

The related lib of hibernate in an article before this article came out

Java Transaction Management Hibernate

You also need to add the spring lib package and the following dependency packages

org.aopalliance

org.aspectj

org.apache.commons

The version of Spring is Spring 4.1.5.

Dependency packages can also be downloaded from the Spring official website, with names similar to spring-framework-3.0.2.RELEASE-dependencies

Theoretical knowledge

After the integration of Spring and Hibernate, when performing database operations through Hibernate API, I found that opensession, close, beginTransaction, and commit are required every time. These are repetitive tasks, and we can leave the transaction management part to the spring framework.

After using spring to manage transactions, you no longer need to call beginTransaction and commit in dao, nor do you need to call session.close(), use API sessionFactory.getCurrentSession()To replace sessionFactory.openSession()

* 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>

Detailed explanation of the transaction attributes of the Propagation class in Spring:

PROPAGATION_REQUIRED: Supports the current transaction. If there is no transaction currently, create a new one affairs. This is the most common choice.

PROPAGATION_SUPPORTS: Supports the current transaction. If there is no transaction currently, it will be executed in a non-transactional manner.

PROPAGATION_MANDATORY: Supports the current transaction. If there is no current transaction, an exception will be thrown.

PROPAGATION_REQUIRES_NEW: Create a new transaction. If a transaction currently exists, suspend the current transaction.

PROPAGATION_NOT_SUPPORTED: Perform operations in a non-transactional manner. If a transaction currently exists, suspend the current transaction.

PROPAGATION_NEVER: Executed in a non-transactional manner, if a transaction currently exists, an exception will be thrown.

PROPAGATION_NESTED: Supports the current transaction. If the current transaction exists, a nested transaction will be executed. If there is no current transaction, a new transaction will be created.

Spring can use xml for configuration or annotation declaration for transaction management.

xml mode configuration transaction code example

##The code structure is as follows:

Detailed code explanation of Spring and Hibernate for Java transaction management learning

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:context="http://www.springframework.org/schema/context" 
 xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" 
 xmlns:tx="http://www.springframework.org/schema/tx" 
 xmlns:aop="http://www.springframework.org/schema/aop" 
 xsi:schemaLocation=" 
  http://www.springframework.org/schema/util 
  http://www.springframework.org/schema/util/spring-util-3.1.xsd 
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.1.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 
  http://www.springframework.org/schema/tx 
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 
 
 <context:component-scan base-package="com.oscar999.trans.sprhib" /> 
 <context:property-placeholder location="classpath:/com/oscar999/trans/sprhib/config.properties" /> 
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
  destroy-method="close"> 
  <!-- Connection Info --> 
  <property name="driverClassName" value="${jdbc.driver}" /> 
  <property name="url" value="${jdbc.url}" /> 
  <property name="username" value="${jdbc.username}" /> 
  <property name="password" value="${jdbc.password}"></property> 
 </bean> 
 
 <bean id="sessionFactory" 
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
  <property name="dataSource" ref="dataSource"></property> 
  <property name="hibernateProperties"> 
   <props> 
    <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> 
    <prop key="hibernate.hbm2ddl.auto">update</prop> 
    <prop key="hibernate.show_sql">true</prop> 
    <prop key="hibernate.format_sql">true</prop> 
    <prop key="hibernate.jdbc.batch_size">20</prop> 
    <prop key="hibernate.enable_lazy_load_no_trans">true</prop> 
    <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> 
    <prop key="jdbc.use_streams_for_binary">true</prop> 
   </props> 
  </property> 
  <property name="packagesToScan"> 
   <list> 
    <value>com.oscar999.trans.sprhib.model</value> 
   </list> 
  </property> 
 </bean> 
 
 <!-- Transaction --> 
 <bean id="transactionManager" 
  class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
  <property name="sessionFactory" ref="sessionFactory" /> 
 </bean> 
 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
  <tx:attributes> 
   <tx:method name="save*" propagation="REQUIRED" /> 
   <tx:method name="*" read-only="true" /> 
  </tx:attributes> 
 </tx:advice> 
 <aop:config proxy-target-class="true"> 
  <aop:pointcut expression="execution(* com.oscar999.trans.sprhib.dao.ProductDAOImpl.*(..))" id="pointcut" /> 
  <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /> 
 </aop:config> 
 
</beans>

config.properties

jdbc.driver=oracle.jdbc.driver.OracleDriver 
jdbc.url=jdbc:oracle:thin:@12.6.18.43:1521:orcl 
jdbc.username= 
jdbc.password=oracle

Product.Java

/** 
 * @Title: Product.java 
 * @Package com.oscar999.trans.hibernate 
 * @Description: 
 * @author XM 
 * @date Feb 15, 2017 1:44:47 PM 
 * @version V1.0 
 */ 
package com.oscar999.trans.sprhib.model; 
 
import java.io.Serializable; 
 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 
 
/** 
 * @author XM 
 * 
 */ 
@Entity 
@Table(name = "TEST_PRODUCT") 
public class Product implements Serializable { 
 
 public Product() { 
 } 
 
 @Id 
 @Column(name = "ID") 
 private Integer id; 
 
 @Column(name = "NAME") 
 private String name; 
 
 @Column(name = "PRICE") 
 private String price; 
 
 private static final long serialVersionUID = 1L; 
 
 public Integer getId() { 
  return id; 
 } 
 
 public void setId(Integer id) { 
  this.id = id; 
 } 
 
 public String getName() { 
  return name; 
 } 
 
 public void setName(String name) { 
  this.name = name; 
 } 
 
 public String getPrice() { 
  return price; 
 } 
 
 public void setPrice(String price) { 
  this.price = price; 
 } 
 
}

ProductDAOImpl.java

/** 
 * @Title: ProductDAOImpl.java 
 * @Package com.oscar999.trans.sprhib 
 * @Description: 
 * @author XM 
 * @date Feb 15, 2017 4:15:09 PM 
 * @version V1.0 
 */ 
package com.oscar999.trans.sprhib.dao; 
 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
 
import com.oscar999.trans.sprhib.model.Product; 
 
/** 
 * @author XM 
 * 
 */ 
@Repository 
public class ProductDAOImpl { 
 
 @Autowired 
 private SessionFactory sessionFactory; 
 
 public Product findProductById(int id) { 
  Session session = sessionFactory.getCurrentSession(); 
  Product product = (Product) session.get(Product.class, id); 
  return product; 
 } 
  
 public Product saveProduct(Product product) { 
  Session session = sessionFactory.getCurrentSession(); 
  session.save(product); 
  return product; 
 } 
}

ProductServiceImpl.java

package com.oscar999.trans.sprhib; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
 
import com.oscar999.trans.sprhib.dao.ProductDAOImpl; 
import com.oscar999.trans.sprhib.model.Product; 
 
@Service 
public class ProductServiceImpl { 
 
 @Autowired 
 private ProductDAOImpl productdao; 
 
 public void findProduct(int id) { 
  Product product = productdao.findProductById(id); 
  if (product != null) { 
   System.out.println(product.getName()); 
  } 
 } 
 
 public void saveProduct() { 
  Product product = new Product(); 
  product.setId(2); 
  product.setName("product2"); 
  product.setPrice("price2"); 
  productdao.saveProduct(product); 
 
 } 
}

TestMain.java

/** 
 * @Title: TestMain.java 
 * @Package com.oscar999.trans.sprhib 
 * @Description: 
 * @author XM 
 * @date Feb 15, 2017 3:54:54 PM 
 * @version V1.0 
 */ 
package com.oscar999.trans.sprhib; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
/** 
 * @author XM 
 * 
 */ 
public class TestMain { 
 
 /** 
  * @param args 
  */ 
 public static void main(String[] args) { 
  // TODO Auto-generated method stub 
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/oscar999/trans/sprhib/applicationContext.xml"); 
  ProductServiceImpl productService = applicationContext.getBean(ProductServiceImpl.class); 
  //productService.findProduct(1); 
  productService.saveProduct(); 
 } 
 
}

The description is as follows:

get can be done without transaction


If there is no insertion or update, the update will not be successful

Declarative mode configuration transaction

Needs to be set in xml configuration


Thing annotation method: @Transactional


When marked on the class In the previous example, all methods in the marked class perform transaction processing. The following code performs transaction processing in the service layer (it is a better way to configure transactions for the Service layer, because a Service layer method operation can be associated with multiple DAO operations. In Service The layer executes these Dao operations. If the multi-DAO operations fail, all are rolled back, and if they succeed, they are all submitted.)

@Service


 @Transactional


 public class UserServiceImpl implements UserService {


  @Autowired


  private UserDao userDao;


 
  public User getUserById(int id) {


   return userDao.findUserById(id);


  }


 }

When some methods in the class do not require things:

@Service


 @Transactional


 public class UserServiceImpl implements UserService {


  @Autowired


  private UserDao userDao;


 
  @Transactional(propagation = Propagation.NOT_SUPPORTED)


  public User getUserById(int id) {


   return userDao.findUserById(id);


  }

Summarize

The above is the detailed content of Detailed code explanation of Spring and Hibernate for Java transaction management learning. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

Why is Java considered a platform-independent language?Why is Java considered a platform-independent language?Apr 27, 2025 am 12:03 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),whichexecutesbytecodeonanydevicewithaJVM.1)Javacodeiscompiledintobytecode.2)TheJVMinterpretsandexecutesthisbytecodeintomachine-specificinstructions,allowingthesamecodetorunondifferentp

How can graphical user interfaces (GUIs) present challenges for platform independence in Java?How can graphical user interfaces (GUIs) present challenges for platform independence in Java?Apr 27, 2025 am 12:02 AM

Platform independence in JavaGUI development faces challenges, but can be dealt with by using Swing, JavaFX, unifying appearance, performance optimization, third-party libraries and cross-platform testing. JavaGUI development relies on AWT and Swing, which aims to provide cross-platform consistency, but the actual effect varies from operating system to operating system. Solutions include: 1) using Swing and JavaFX as GUI toolkits; 2) Unify the appearance through UIManager.setLookAndFeel(); 3) Optimize performance to suit different platforms; 4) using third-party libraries such as ApachePivot or SWT; 5) conduct cross-platform testing to ensure consistency.

What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.