【问题标题】:Spring JPA getting new Transaction for Every method call and transaction not work properlySpring JPA 为每个方法调用和事务获取新事务无法正常工作
【发布时间】:2018-08-31 10:44:58
【问题描述】:

我正在使用 Spring Data JPA 我正在从一个方法中保存多个对象,当保存第一个对象后发生某些事情时,应该回滚第一个保存的对象,但是当我看到我发现获取新事务的日志时没有发生这种情况每个方法调用并在下面提交都是我的服务层方法,在第一个对象持久化后,我在其中创建了“nullPointerException”

 @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void testTransaction(HashMap<String, Object> hashMap) throws Exception {
        try {
            VendorType  vendorType  = (VendorType) hashMap.get("vendorType");
            RenewalType renewalType = (RenewalType) hashMap.get("renewalType");

            vendorTypeService.registerNewVendorType(vendorType);
            Vehicle vehicle = null;
            vehicle.getCompany_Id();
            renewalTypeService.registerNewRenewalType(renewalType);
        } catch (Exception e) {

            System.err.println("inside method exception "+e);
        }
    }

下面是不同服务方法中定义的 registerVendor 方法

 @org.springframework.transaction.annotation.Transactional
public VendorType registerNewVendorType(final VendorType accountDto) throws Exception {

    return VendorTyperepository.save(accountDto);
}

这是我的配置文件 PersistenceJPAConfig.java

 @Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence.properties" })
@ComponentScan({ "org.fleetopgroup.persistence" })
@EnableJpaRepositories(basePackages = "org.fleetopgroup.persistence.dao")
public class PersistenceJPAConfig {

    @Autowired
    private Environment env;

    public PersistenceJPAConfig() {
        super();
    }

    //

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "org.fleetopgroup.persistence.model" });
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        return dataSource;
    }


    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    final Properties additionalProperties() {
        final Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
        hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
        return hibernateProperties;
    }

Below is Log Trace : 

web - 2018-03-22 10:53:15,566 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Initializing transaction synchronization
web - 2018-03-22 10:53:15,566 [http-nio-8080-exec-5] TRACE o.s.t.i.TransactionInterceptor - Getting transaction for [org.fleetopgroup.persistence.service.VehicleService.testTransaction]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] DEBUG o.s.t.a.AnnotationTransactionAttributeSource - Adding transactional method 'org.fleetopgroup.persistence.service.VendorTypeService.registerNewVendorType' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@23976e80] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@45f6c4a9] bound to thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@30496576] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@6007487a] bound to thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.i.TransactionInterceptor - Getting transaction for [org.fleetopgroup.persistence.service.VendorTypeService.registerNewVendorType]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Bound value [org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$DefaultCrudMethodMetadata@5dbd844] for key [public abstract java.lang.Object org.springframework.data.repository.CrudRepository.save(java.lang.Object)] to thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@23976e80] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@45f6c4a9] bound to thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@30496576] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@6007487a] bound to thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,567 [http-nio-8080-exec-5] TRACE o.s.t.i.TransactionInterceptor - Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
web - 2018-03-22 10:53:15,574 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@23976e80] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@45f6c4a9] bound to thread [http-nio-8080-exec-5]
Hibernate: insert into vendortype (companyId, createdBy, createdOn, lastModifiedBy, lastModifiedOn, markForDelete, vendor_TypeName) values (?, ?, ?, ?, ?, ?, ?)
web - 2018-03-22 10:53:15,625 [http-nio-8080-exec-5] TRACE o.s.t.i.TransactionInterceptor - Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
web - 2018-03-22 10:53:15,625 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Removed value [org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$DefaultCrudMethodMetadata@5dbd844] for key [public abstract java.lang.Object org.springframework.data.repository.CrudRepository.save(java.lang.Object)] from thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,625 [http-nio-8080-exec-5] TRACE o.s.t.i.TransactionInterceptor - Completing transaction for [org.fleetopgroup.persistence.service.VendorTypeService.registerNewVendorType]
inside method exception java.lang.NullPointerException
web - 2018-03-22 10:53:15,625 [http-nio-8080-exec-5] TRACE o.s.t.i.TransactionInterceptor - Completing transaction for [org.fleetopgroup.persistence.service.VehicleService.testTransaction]
web - 2018-03-22 10:53:15,626 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Clearing transaction synchronization
web - 2018-03-22 10:53:15,627 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Removed value [org.springframework.orm.jpa.EntityManagerHolder@23976e80] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@45f6c4a9] from thread [http-nio-8080-exec-5]
web - 2018-03-22 10:53:15,627 [http-nio-8080-exec-5] TRACE o.s.t.s.TransactionSynchronizationManager - Removed value [org.springframework.jdbc.datasource.ConnectionHolder@30496576] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@6007487a] from thread [http-nio-8080-exec-5]

MyController.java

@Controller
public class MyControllerextends MainActivity {

   @Autowired
    private IVehicleService vehicleService;

*@RequestMapping(value = "/test", method = RequestMethod.GET)
    public ModelAndView test() throws Exception {
        HashMap<String, Object>         model           = new HashMap<String, Object>();
        try {
            CustomUserDetails   userDetails =       (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            VendorType  vendorType  = new  VendorType();
            vendorType.setVendor_TypeName("TEST");
            vendorType.setCreatedBy("manish");
            vendorType.setCreatedOn(new Timestamp(System.currentTimeMillis()));
            vendorType.setCompanyId(userDetails.getCompany_id());

            RenewalType renewalType = new RenewalType();
            renewalType.setRenewal_Type("test type");
            renewalType.setCreatedBy("manish");
            renewalType.setCreatedOn(new Timestamp(System.currentTimeMillis()));
            renewalType.setCompanyId(userDetails.getCompany_id());
            model.put("renewalType", renewalType);
            model.put("vendorType", vendorType);
            vehicleService.testTransaction(model);
        }catch (Exception e) {
            throw new Exception();
        }
        return new ModelAndView("redirect:/vehicle/1/1.in?danger=true");
}

IVehicleService.java

public interface IVehicleService {
   public void testTransaction(HashMap<String, Object> hashMap) throws Exception;
}

VehicleService.java

 @Service("VehicleService")
    @Transactional (readOnly = true)
    public class VehicleService implements IVehicleService {

@Autowired
    private IVendorTypeService      vendorTypeService;

       @Override
        @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
        public void testTransaction(HashMap<String, Object> hashMap) throws Exception {
                try {
                    RenewalType renewalType =   (RenewalType) hashMap.get("renewalType");
                    VendorType  vendorType =    (VendorType) hashMap.get("vendorType");

                    vendorTypeService.registerNewVendorType(vendorType);
                    Vehicle vehicle = null;
                    vehicle.getCompany_Id();
                } catch (Exception e) {
                    throw new Exception();
                }
        }
    }

IVendorTypeService.java

public interface IVendorTypeService {
  public VendorType registerNewVendorType(VendorType GET_DocType) throws Exception;
}

VendorTypeService.java

@Service
public class VendorTypeService implements IVendorTypeService {
    @Autowired
    private VendorTypeRepository VendorTyperepository;


    // API

    @org.springframework.transaction.annotation.Transactional
    public VendorType registerNewVendorType(final VendorType accountDto) throws Exception {

        return VendorTyperepository.save(accountDto);
    }
}

VendorTypeRepository.java

@Repository
public interface VendorTypeRepository extends JpaRepository<VendorType, Long> {

}

【问题讨论】:

  • 您不会重新抛出 NullPointerException。你只要抓住它。
  • @SimonMartinelli 我没听懂你想说什么?
  • } catch (Exception e) { System.err.println("内部方法异常 "+e); } 你捕捉到异常所以事务永远不会回滚
  • @SimonMartinelli 在执行此操作后也不会回滚,因为您可以查看日志跟踪,仅在保存第一个对象后它正在提交并为所有方法调用创建差异事务
  • 休眠:插入 vendortype (companyId, createdBy, createdOn, lastModifiedBy, lastModifiedOn, markForDelete, vendor_TypeName) 值 (?, ?, ?, ?, ?, ?, ?) web - 2018-03- 22 13:53:36,142 [http-nio-8080-exec-144] TRACE ostiTransactionInterceptor - 为 [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save] 完成交易

标签: spring hibernate jpa spring-transactions transactional


【解决方案1】:

问题在于休眠配置中的 MySql 数据库存储引擎方言属性在更改为 MySQLInnoDBDialect 后是 MySQLDialect 并且将表引擎更改为 InnoDB 现在它工作正常

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2019-10-05
    相关资源
    最近更新 更多