Added changes to show transaction roll back

This commit is contained in:
Amitabh Tiwari 2020-12-25 09:06:51 +05:30
parent 7f19907f51
commit 2d2a64acbe
3 changed files with 97 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,24 @@
package com.baeldung.spring.transaction;
import java.sql.SQLException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Repository;
import com.baeldung.spring.hibernate.AbstractHibernateDao;
@Repository
public class CourseDao extends AbstractHibernateDao<Course> {
public CourseDao() {
super();
setClazz(Course.class);
}
public Course createWithRuntimeException(final Course entity) {
throw new DataIntegrityViolationException("Throwing exception for demoing Rollback!!!");
}
public Course createWithCheckedException(final Course entity) throws SQLException {
throw new SQLException("Throwing exception for demoing Rollback!!!");
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.spring.transaction;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
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.createWithRuntimeException(course);
}
@Transactional(rollbackFor = { SQLException.class })
public void createCourseDeclarativeWithCheckedException(Course course) throws SQLException {
courseDao.createWithCheckedException(course);
}
public void createCourseDefaultRatingProgramatic(Course course) {
try {
courseDao.createWithRuntimeException(course);
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
public Course findById(Long id) {
return courseDao.findOne(id);
}
}