Spring数据@Transactional不回滚
我使用SpringMVC和SpringJPA开发了我的第一个应用程序。我在使用@Transactional注释时遇到问题。我用@Transactional注释了我的一个服务方法,并在该方法中抛出异常,因为我希望它被回滚,但它没有 以下是我的配置文件和我的类文件内容: app-context.xmlSpring数据@Transactional不回滚,spring,jpa,repository,rollback,transactional,Spring,Jpa,Repository,Rollback,Transactional,我使用SpringMVC和SpringJPA开发了我的第一个应用程序。我在使用@Transactional注释时遇到问题。我用@Transactional注释了我的一个服务方法,并在该方法中抛出异常,因为我希望它被回滚,但它没有 以下是我的配置文件和我的类文件内容: app-context.xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframe
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="id.co.cslgroup"/>
<jpa:repositories base-package="id.co.cslgroup"/>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="defaultAutoCommit" value="false"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="kms-pu"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaAdapter"/>
</bean>
<bean id="customUserDetailsService" class="id.co.cslgroup.kms.svc.CustomUserDetailsService" />
<bean id="hibernateJpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<context:property-placeholder location="classpath:/META-INF/database.properties"/>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven conversion-service="conversionService"/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name ="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<beans:property name="converters">
<beans:list>
<beans:bean class="id.co.cslgroup.kms.svc.AttributeConverter"/>
<beans:bean class="id.co.cslgroup.kms.svc.KeyClassConverter"/>
<beans:bean class="id.co.cslgroup.kms.svc.KeyTypeConverter"/>
<beans:bean class="id.co.cslgroup.kms.svc.KeyProfileConverter"/>
<beans:bean class="id.co.cslgroup.kms.svc.StringToDateConverter"/>
<beans:bean class="id.co.cslgroup.kms.svc.StringToIntegerConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<context:component-scan base-package="id.co.cslgroup" />
</beans:beans
AttributeRepository.java
public interface AttributeRepository extends JpaRepository<Attribute, Long> {
}
Attribute.java
package id.co.cslgroup.kms.entity;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
public class Attribute extends AbstractPersistable<Long> {
@Column(nullable = false, unique = true)
@NotEmpty
@NotNull
private String code;
@Column(nullable = false)
@NotEmpty
@NotNull
private String name;
@OneToMany(fetch= FetchType.LAZY, mappedBy = "pk.attribute")
private Collection<ProfileAttribute> profileAttribute;
@Column(nullable = false)
@Temporal(javax.persistence.TemporalType.DATE)
private Date createTime;
@Column(nullable = false)
private String createBy;
@Column(nullable = true)
@Temporal(javax.persistence.TemporalType.DATE)
private Date updateTime;
@Column(nullable = true)
private String updateBy;
@Column(nullable = false)
private Boolean status;
@Version
@Column
private Long version = 0L;
// @ManyToMany(cascade=CascadeType.ALL)
// @JoinTable(name = "key_attributes",
// joinColumns = {@JoinColumn(name="attribute_id")},
// inverseJoinColumns = {@JoinColumn(name="key_table_id")}
// )
// private Set<KeyTable> keytables;
//
// public Set<KeyTable> getKeyTables(){
// return keytables;
// }
//
// public void setKeyTables(Set<KeyTable> kt){
// this.keytables = kt;
// }
// @Transient
// private String[] testArr;
//
// public String[] getTestArr() {
// return testArr;
// }
//
// public void setTestArr(String[] ta) {
// this.testArr = ta;
// }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getCreateTime() {
return createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public Long getVersion() {
return version;
}
@PrePersist
private void prePersist() {
this.createBy = "Admin";
this.createTime = new Date();
}
@PreUpdate
private void preUpdate() {
this.updateBy = "Admin";
this.updateTime = new Date();
}
/**
* @return the keyProfiles
*/
public Collection<ProfileAttribute> getProfileAttribute() {
return profileAttribute;
}
/**
* @param keyProfiles the keyProfiles to set
*/
public void setProfileAttribute(Collection<ProfileAttribute> profileAttribute) {
this.profileAttribute = profileAttribute;
}
}
在AttributeService.java的保存方法中,您可以找到:
t = attributeRepository.save(t);
if(t.getId() > 1){
throw new Exception();
}
因此,在调用save之后,我立即抛出一个异常,但随后我检查了数据库,它没有回滚
我真的很感谢你们的帮助,
谢谢 您的
属性
类没有id
字段。它是否来自AbstractPersistable
您能否展示一下您是如何注释ID
字段的?它是自动生成的吗
根据以上所述,可能有几种情况。
1.您的Id
永远不会变为大于1,并且永远不会抛出excepion
我会建议尝试下面的代码,并让我知道,即使在它之后,事务没有回滚
t = attributeRepository.save(t);
throw new Exception();
另外,显示有关id
如何在属性类中映射的代码将对您有所帮助
另外,调用AttributeService Save
方法的方式和位置也会影响事务。这部分代码也会有帮助。我发现了问题。在app-context.xml和servlet-context.xml中,两者都有
。该标签将导致此链接中解释的问题:
.请显示调用AttributeService.save()
method的代码。我在AttributeControl类中调用了它。我已经编辑了我的问题,谢谢。@ChrismaAndhika您能给我们展示一下AtributeRepositoy的实现吗?您是否也在其上使用了事务注释?或者类似于在里面提交的东西?您的调用代码在我看来很好..id来自AbstractPersistable,它是自动生成的。我还调试了AttributeService和抛出新异常();行被执行。我在AttributeControl中调用了save方法。@ChrismaAndhika调用AttributeService保存方法的方式和地点也会影响事务。这部分代码也会有帮助。你能把这个加到问题上吗
@Service
@Transactional
public class AttributeService {
@Autowired
private AttributeRepository attributeRepository;
@Transactional(readOnly=false,propagation= Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
public AttributeMasterForm save(AttributeMasterForm attForm) throws Exception{
Attribute t = new Attribute();
AttributeMasterForm masterForm = new AttributeMasterForm();
//transfer value from master form to entity
t = updateValue(t,attForm);
//persist to database
t = attributeRepository.save(t);
if(t.getId() > 1){
throw new Exception();
}
return this.convertToMasterForm(t);
}
private AttributeMasterForm convertToMasterForm(Attribute attr){
AttributeMasterForm masterForm = new AttributeMasterForm();
masterForm.setId(attr.getId());
masterForm.setCode(attr.getCode());
masterForm.setName(attr.getName());
masterForm.setStatus(attr.getStatus());
return masterForm;
}
private Attribute updateValue(Attribute attr,AttributeMasterForm attForm){
attr.setCode(attForm.getCode());
attr.setName(attForm.getName());
attr.setStatus(attForm.getStatus());
return attr;
}
}
package id.co.cslgroup.kms.entity;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
public class Attribute extends AbstractPersistable<Long> {
@Column(nullable = false, unique = true)
@NotEmpty
@NotNull
private String code;
@Column(nullable = false)
@NotEmpty
@NotNull
private String name;
@OneToMany(fetch= FetchType.LAZY, mappedBy = "pk.attribute")
private Collection<ProfileAttribute> profileAttribute;
@Column(nullable = false)
@Temporal(javax.persistence.TemporalType.DATE)
private Date createTime;
@Column(nullable = false)
private String createBy;
@Column(nullable = true)
@Temporal(javax.persistence.TemporalType.DATE)
private Date updateTime;
@Column(nullable = true)
private String updateBy;
@Column(nullable = false)
private Boolean status;
@Version
@Column
private Long version = 0L;
// @ManyToMany(cascade=CascadeType.ALL)
// @JoinTable(name = "key_attributes",
// joinColumns = {@JoinColumn(name="attribute_id")},
// inverseJoinColumns = {@JoinColumn(name="key_table_id")}
// )
// private Set<KeyTable> keytables;
//
// public Set<KeyTable> getKeyTables(){
// return keytables;
// }
//
// public void setKeyTables(Set<KeyTable> kt){
// this.keytables = kt;
// }
// @Transient
// private String[] testArr;
//
// public String[] getTestArr() {
// return testArr;
// }
//
// public void setTestArr(String[] ta) {
// this.testArr = ta;
// }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getCreateTime() {
return createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public Long getVersion() {
return version;
}
@PrePersist
private void prePersist() {
this.createBy = "Admin";
this.createTime = new Date();
}
@PreUpdate
private void preUpdate() {
this.updateBy = "Admin";
this.updateTime = new Date();
}
/**
* @return the keyProfiles
*/
public Collection<ProfileAttribute> getProfileAttribute() {
return profileAttribute;
}
/**
* @param keyProfiles the keyProfiles to set
*/
public void setProfileAttribute(Collection<ProfileAttribute> profileAttribute) {
this.profileAttribute = profileAttribute;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package id.co.cslgroup.kms.model;
import java.util.Date;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
/**
*
* @author supriadi
*/
public class AttributeMasterForm {
private Long id;
@NotEmpty
@NotNull
private String code;
@NotEmpty
@NotNull
private String name;
private Date createTime;
private String createBy;
private Date updateTime;
private String updateBy;
private Boolean status;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the status
*/
public Boolean getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(Boolean status) {
this.status = status;
}
/**
* @return the createTime
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param createTime the createTime to set
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* @return the createBy
*/
public String getCreateBy() {
return createBy;
}
/**
* @param createBy the createBy to set
*/
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
/**
* @return the updateTime
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* @param updateTime the updateTime to set
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* @return the updateBy
*/
public String getUpdateBy() {
return updateBy;
}
/**
* @param updateBy the updateBy to set
*/
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
}
t = attributeRepository.save(t);
if(t.getId() > 1){
throw new Exception();
}
t = attributeRepository.save(t);
throw new Exception();