JPA在Spring无法提交事务
- 在SpringConfig中打开事务
import org.springframework.context.annotation.Configuration;
@Configuration
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.service,com.dao,com.util,com.cache")
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement(proxyTargetClass = true)
注意不要导错包,例如
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Configuration;
这两个包可能会搞混,如果导成上面的包,就会导致无法开启事务,但不影响JPA查询语句
- 在Service中加入注解并设置事务回滚
@Service
@Transactional(rollbackFor = java.lang.Exception.class)
在@Transactional注解中如果不配置rollbackFor属性,那么事物只会在遇到RuntimeException的时候才会回滚,加上rollbackFor=Exception.class,可以让事物在遇到非运行时异常时也回滚.
- 最后在Dao和JpaUtil下加入@Repository注解