@Transactional Spring Boot là gì

Spring Hibernate Transaction trong Spring Hibernate. Code ví dụ Spring Hibernate Transaction.

Ở phần trước chúng ta đã tìm hiểu về Spring ORM và code ví dụ với Spring Hibernate

Ở phần này chúng ta sẽ thực hiện quản lý trasaction của các truy vấn thông qua hibernate.

1. Transaction trong Spring Hibernate

(Xem lạiTransaction là gì? Code ví dụ transaction với JDBC)

Để thực hiện quản lý hibernate bởi transactionManager ta khai báo trong file spring config:

Ở trong file DAO, để bật chức năng quản lý transaction ta dùng annotation:@Transactional(rollbackFor = Exception.class)

  • Nếu đặt @Transaction ở đầu class thì tất cả các method trong class đó đều nằm trong 1 transaction.
  • Nếu đặt@Transaction ở đầu method thì chỉ các method đó được nằm trong 1 transaction.
  • rollbackFor = Exception.class: Chỉ rõ khi xảy ra exception nào thì rollback, thông thường chỉ các exception khi truy vấn mới bị rollback như SQLException Ở đây mình đểrollbackFor = Exception.class tức là khi xảy exception bất kì thì đều rollback lại.
  • Những method được nằm trong 1 transaction thì chúng ta sẽ gọisessionFactory.getCurrentSession() để lấy sesion chứ không gọisessionFactory.openSession().

3. Code ví dụ

Ở ví dụ này mình sử dụng:

  • MySQL làm cơ sở dữ liệu (Xem lại:Cài đặt và cấu hình MySQL)
  • Eclipse
  • Maven

Tạo database:

CREATE SCHEMA `demo-spring-hibernate` ; CREATE TABLE `demo-spring-hibernate`.`customer` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NULL, `address` VARCHAR(255) NULL, PRIMARY KEY (`id`));

@Transactional Spring Boot là gì

Tạo maven project:

@Transactional Spring Boot là gì

Thư viện sử dụng:

4.0.0 stackjava.com DemoJDBC 0.0.1-SNAPSHOT org.springframework spring-context 5.0.2.RELEASE org.springframework spring-orm 5.0.2.RELEASE org.hibernate hibernate-core 5.2.12.Final org.hibernate hibernate-entitymanager 5.2.12.Final commons-dbcp commons-dbcp 1.4 mysql mysql-connector-java 5.1.45

File Spring config:

  • org.apache.commons.dbcp.BasicDataSource:chứa các thông tin kết nối tới database
  • org.springframework.orm.hibernate5.LocalSessionFactoryBean: tạo đối tượng sessionFactory.
    • Thuộc tínhpackagesToScan sẽ chỉ định package chứa các file entity map với table trong database (hoặc bạn cũng có thể chỉ rõ các class entity mapping với table bằng thuộc tínhannotatedClasses)
    • Thuộc tính hibernateProperties khai báo file chưa các thông tin config hibernate (hoặc bạn cũng có thể chỉ rõ các thông tin config trong file spring config luôn).
  • : bật transactionMangement
  • beantransactionManager sẽ quản lý transaction cho những truy vấn thông qua sessionFactory

File Hibernate config:

hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hibernate.current_session_context_class=thread hibernate.show_sql=true

File entity:

package stackjava.com.springhibernate.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "customer") public class Customer { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "name") private String name; @Column(name = "address") private String address; public Customer() { } public Customer(int id, String name, String address) { this.id = id; this.name = name; this.address = address; } public Customer(String name, String address) { this.name = name; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }

File DAO:

package stackjava.com.springhibernate.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import stackjava.com.springhibernate.entities.Customer; @Repository(value = "customerDAO") @Transactional(rollbackFor = Exception.class) public class CustomerDAO { @Autowired private SessionFactory sessionFactory; public void test(Customer customer) throws Exception { this.save(customer); this.demoException(); } public void save(Customer customer) { Session session = this.sessionFactory.getCurrentSession(); session.save(customer); System.out.println("save done!"); } public void demoException() throws Exception { // do something throw new Exception("demo throw exception"); } }
  • @Transactional(rollbackFor = Exception.class): Annotation @Transaction để ở đầu method nên tất cả các method của class CustomerDAO đều nằm trong transaction,
  • rollbackFor = Exception.classtức là rollback khi xảy ra bất kì exception nào.

Demo:

package stackjava.com.springhibernate.main; import org.springframework.context.support.ClassPathXmlApplicationContext; import stackjava.com.springhibernate.dao.CustomerDAO; import stackjava.com.springhibernate.entities.Customer; public class MainApp { public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO"); Customer customer = new Customer("Rooney", "Manchester"); customerDAO.test(customer); context.close(); } }

Kết quả:

@Transactional Spring Boot là gì

Hành động insert thành công nhưng sau đấy xảy ra lỗi nên dữ liệu sẽ bị rollback lại, không được save vào database nữa:

@Transactional Spring Boot là gì

Spring Hibernate Transaction trong Spring Hibernate. Code ví dụ Spring Hibernate Transaction.

Okay, Done!

Download code ví dụ trên tại đây.