Merge pull request #10342 from amitiw4u/BAEL-4624-SpringTransactionRollback

Added changes to show transaction roll back
This commit is contained in:
Eric Martin 2021-01-12 19:40:36 -06:00 committed by GitHub
commit f89f2b19a6
3 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.spring.transaction;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "course")
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
private Long id;
public Course() {
}
public Course(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.spring.transaction;
import org.springframework.stereotype.Repository;
import com.baeldung.spring.hibernate.AbstractHibernateDao;
@Repository
public class CourseDao extends AbstractHibernateDao<Course> {
public CourseDao() {
super();
setClazz(Course.class);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.spring.transaction;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@Service
public class CourseService {
@Autowired
private CourseDao courseDao;
@Transactional
public void createCourseDeclarativeWithRuntimeException(Course course) {
courseDao.create(course);
throw new DataIntegrityViolationException("Throwing exception for demoing Rollback!!!");
}
@Transactional(rollbackFor = { SQLException.class })
public void createCourseDeclarativeWithCheckedException(Course course) throws SQLException {
courseDao.create(course);
throw new SQLException("Throwing exception for demoing Rollback!!!");
}
public void createCourseDefaultRatingProgramatic(Course course) {
try {
courseDao.create(course);
throw new DataIntegrityViolationException("Throwing exception for demoing Rollback!!!");
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
@Transactional(noRollbackFor = { SQLException.class })
public void createCourseDeclarativeWithNoRollBack(Course course) throws SQLException {
courseDao.create(course);
throw new SQLException("Throwing exception for demoing Rollback!!!");
}
}