Spring JPA 为每个方法调用和事务获取新事务无法正常工作

Spring JPA getting new Transaction for Every method call and transaction not work properly

i am using Spring Data JPA i am saving multiple objects from one method and when something happens after saving the first object then first saved object should be rollback but this is not happening when I see the logs I found that getting new transaction for every method call and committing it below is my service layer method in which I created "nullPointerException" after the first object persisted

 @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> {

}

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

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect