Springboot @Transcational не получает отката - PullRequest
1 голос
/ 18 марта 2020

Я новичок в Springboot и работаю над проектом. Я использую Springboot с hibernate, JPA и hikariCP для операций mysql DB. В настоящее время у меня есть два источника данных, в которых я не смог откатить транзакцию, которую я написал внутри службы. Я перепробовал все, что мог найти, но не смог выяснить, чего мне не хватает. Любая помощь будет оценена и простите мои ошибки, и я очень открыт для предложений. Спасибо.

@SpringBootApplication
public class AdminModuleApplication {
public static void main(String[] args) 
    {
        SpringApplication.run(AdminModuleApplication.class, args);
    }   
}
@Configuration
@PropertySource({ "classpath:acc_payDB_properties.properties" })
@EnableJpaRepositories(
    basePackages = "com.pinnacle.accpay.dao", 
    entityManagerFactoryRef = "accpayEntityManager", 
    transactionManagerRef = "accpayTransactionManager"
)
public class acc_payDBConfig 
{
    @Autowired
    private Environment env;

    @Bean
    public LocalContainerEntityManagerFactoryBean accpayEntityManager() 
    {
        String packageList[]= {"com.pinnacle.accpay.model","com.pinnacle.admin.model"};
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(accpayDataSource());
        em.setPackagesToScan(packageList);
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.hbm2ddl.auto", "none");
        Properties jpaProperties2 = new Properties();
        jpaProperties2.setProperty("connection.provider_class","org.hibernate.hikaricp.internal.HikariCPConnectionProvider");
        em.setJpaProperties(jpaProperties2);
        return em;
    }


    @Bean
    public DataSource accpayDataSource() 
    {

        HikariDataSource dataSource = new HikariDataSource(); 
        dataSource.setDriverClassName(env.getProperty("jdbc.driver-class-name"));
        dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        dataSource.setCatalog("acc_pay");
        //HikariCP specific properties. Remove if you move to other connection pooling library.
        dataSource.setConnectionTimeout(20000);
        dataSource.setMaximumPoolSize(20);
        dataSource.setMinimumIdle(10);
        dataSource.setIdleTimeout(20000);
        dataSource.setMaxLifetime(40000);
        dataSource.setAutoCommit(false);
        dataSource.addDataSourceProperty("cachePrepStmts", true);
        dataSource.addDataSourceProperty("prepStmtCacheSize", 25000);
        dataSource.addDataSourceProperty("prepStmtCacheSqlLimit", 20048);
        dataSource.addDataSourceProperty("useServerPrepStmts", true);
        dataSource.addDataSourceProperty("initializationFailFast", true);
        dataSource.setPoolName("ACCPAY DB_HIKARICP_CONNECTION_POOL");
        dataSource.addDataSourceProperty("useLocalTransactionState", false);
        return new HikariDataSource(dataSource);

    }

    @Bean
    public PlatformTransactionManager accpayTransactionManager() 
    {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(accpayEntityManager().getObject());
        return transactionManager;
    }
}


@Service
public class TranscationReceptionService {
    @Autowired
    PO_TXN_MasterBeanRepository po_TXN_MasterBeanRepository;

    @Autowired
    GRN_TXN_MasterBeanRepository grn_TXN_MasterBeanRepository;

    @Autowired
    Invoice_TXN_MasterBeanRepository invoice_TXN_MasterBeanRepository;

    @Autowired
    POEventLogRepository poEventLogRepository;

    @Autowired
    InvoiceEventLogRepository invoiceEventLogRepository;

    @Autowired
    GRNEventlogRepository grnEventlogRepository;

    @Autowired
    PO_GRN_INVBeanRepository po_GRN_INVBeanRepository;

    @Autowired
    LinkEventLogBeanRepository linkEventLogBeanRepository;

    @Autowired
    ScheduledJob scheudledJob;

    @Autowired
    acc_payDBConfig acc_paydbConfig;

    @Value("${in_process_status}")
    private String in_process_status;


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateMatchStatus(Long poId, Long invoiceId, String poStatus, String invoiceStatus)
    {
        try
        {

        po_TXN_MasterBeanRepository.setPOStatusAfterMatching(poStatus, poId, invoiceId);

        POEventLogBean poEventLogBean = new POEventLogBean();
        poEventLogBean.setPo_id(poId); poEventLogBean.setEvent_time(LocalDateTime.now().toString());
        poEventLogBean.setStatus(poStatus); 
        poEventLogRepository.save(poEventLogBean);

        po_GRN_INVBeanRepository.setInvoiceNumber(poId, invoiceId);

        Long linkId = po_GRN_INVBeanRepository.getLinkIdfromPONumber(poId);

        LinkEventLogBean linkEventLogBean=new LinkEventLogBean();
        linkEventLogBean.setLink_id(linkId); 
        linkEventLogBean.setEvent_time(LocalDateTime.now().toString());
        linkEventLogBean.setStatus("");
        linkEventLogBeanRepository.save(linkEventLogBean);

        invoice_TXN_MasterBeanRepository.setInvoiceStatusAfterMatching(poId, invoiceStatus, invoiceId);

        InvoiceEventLogBean invoiceEventLogBean=new InvoiceEventLogBean();
        invoiceEventLogBean.setInv_id(invoiceId); invoiceEventLogBean.setEvent_time(LocalDateTime.now().toString());
        invoiceEventLogBean.setStatus(invoiceStatus);
        invoiceEventLogRepository.save(invoiceEventLogBean);
        }
        catch (Exception e) 
        {

        }
    }

}

@Transactional
@Repository
public interface PO_TXN_MasterBeanRepository extends JpaRepository<PO_TXN_MasterBean, Long> 
{

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("UPDATE PO_TXN_MasterBean p SET p.status= :status, p.inv_id= :invId WHERE p.po_id = :pId")
    public void setPOStatusAfterMatching(@Param("status") String status, @Param("pId") Long poId, @Param("invId") Long invoiceId);
}

@Transactional
@Repository
public interface POEventLogRepository extends JpaRepository<POEventLogBean, Integer> 
{

}

@Transactional
@Repository
public interface PO_GRN_INVBeanRepository extends JpaRepository<PO_GRN_INVBean, Long>
{

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query("UPDATE PO_GRN_INVBean p SET p.inv_id= :invId WHERE p.po_id = :pId")
    public void setInvoiceNumber(@Param("pId") Long poId, @Param("invId") Long invoiceId);

    @Query("SELECT  p.link_id FROM PO_GRN_INVBean p WHERE p.po_id = :pId")
    public Long getLinkIdfromPONumber(@Param("pId") Long poId);
}


@Transactional
@Repository
public interface LinkEventLogBeanRepository extends JpaRepository<LinkEventLogBean, Long>
{

}

@Repository
@Transactional
public interface Invoice_TXN_MasterBeanRepository extends JpaRepository<Invoice_TXN_MasterBean, Long> 
{
    @Modifying(clearAutomatically = true)
    @Transactional
    @Query("UPDATE Invoice_TXN_MasterBean i SET i.po_id = :pid, i.status =:status WHERE i.inv_id = :inid")
    public void setInvoiceStatusAfterMatching(@Param("pid") Long pid, @Param("status") String status, @Param("inid") Long inId);
}

@Repository
public interface InvoiceEventLogRepository extends JpaRepository<InvoiceEventLogBean, Integer>
{

}

1 Ответ

0 голосов
/ 19 марта 2020

Откат транзакции не работает должным образом, поскольку исключение обрабатывается блоком try-catch в TranscationReceptionService.updateMatchStatus(). Это не позволяет каркасу пружины быть в курсе возникшего исключения и, следовательно, не приводит к откату.

...