Spring JPA获取新的Transaction for Every方法调用和事务无法正常工作

时间:2018-03-22 05:26:24

标签: spring hibernate jpa spring-transactions transactional

  

我正在使用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> {

}

1 个答案:

答案 0 :(得分:0)

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

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect