Spring Jpa @Transactional无法正常工作

时间:2017-11-15 10:40:38

标签: java spring hibernate jpa

如果一个或多个查询失败,我正在尝试实现事务回滚。所以我在我的服务实现类上注释了@Transactional。我故意发送了错误的数据类型amountpaid1(在这种情况下为String,Double是正确的数据类型)。

但是现在,我的第一个更新查询加上challan上的插入成功完成。
第二个查询,即query1无法更新,因为它收到错误的数据类型所以我希望整个事务回滚。

存储库

@Repository
public class UpdatePaymentImpl implements UpdatePayment {


@PersistenceContext
EntityManager em;

public PaymentResponse getFcgoApiResponse(FcgoUpdateParam updateParam){
    PaymentResponse paymentResponse = new PaymentResponse();
    try {
        final String uri = "http://a.b.c.d:xxxx/FcgoApi/api/savePayment";
        RestTemplate restTemplate = new RestTemplate();
        paymentResponse = restTemplate.postForObject(uri, updateParam, 
        PaymentResponse.class);
            if (paymentResponse.getVoucherNo() != null) {
                int status = updatePayment(updateParam, 
                paymentResponse.getVoucherNo());
                if (status == 0) {
                    vc.setVoucherNo(paymentResponse.getVoucherNo());
                }
            }
    }catch (Exception ex){
        ex.printStackTrace();
        logger.info(ex.getMessage());
    }
    return paymentResponse;

}


    @Transactional
    public int updatePayment(FcgoUpdateParam updateParam, String voucherno){

        try{
            String amountPaid1 = updateParam.getAmountPaid();
            Double amountPaid=Double.parseDouble(updateParam.getAmountPaid());
            String masterId= updateParam.getMasterId();
            String advCode=updateParam.getAdvCode();
            long uuid = getUniqueID();
            logger.info("generated uuid "+uuid);
            DateFormat dateFormat =new SimpleDateFormat("dd-MMM-yy h.mm.ss.000000000 a");
            SimpleDateFormat dms = new SimpleDateFormat("dd-MM-yyyy");
            String cdate = updateParam.getChallanDate();
            Date ddate= dms.parse(cdate);
            String challandate = dateFormat.format(ddate);
            String office = updateParam.getOffice();
            String username = updateParam.getUsername();
            Long id = getIdOnChallanTable()+1L;

            String challanid = String.valueOf(uuid);
            ChallanEntity challanEntity = new ChallanEntity();
            challanEntity.setAdvtcode(updateParam.getAdvCode());
            challanEntity.setAmount(amountPaid);
            challanEntity.setName(updateParam.getName());
            challanEntity.setOffice(office);
            challanEntity.setUsername(username);
            challanEntity.setStatus(updateParam.getStatus());
            challanEntity.setChallandate(challandate);
            challanEntity.setChallanid(uuid);
            challanEntity.setChallantime("null");
            challanEntity.setVoucherno(voucher no);
            Query query= em.createQuery("update 
            CandidateappearagainstadvtcodeEntity cd set 
     cd.paymentstatus='Completed',cd.amountpaid=:depoFee,cd.challanid=:challanid
             where cd.studentmasterid=:masterid and cd.advertisementcode=:advCode");
            logger.info("update parameter advt code: "+updateParam.getAdvCode());
            query.setParameter("depoFee",updateParam.getAmountPaid());
            query.setParameter("challanid",challanid);
            query.setParameter("masterid",masterId);
            query.setParameter("advCode",advCode)
            .executeUpdate();
            Query query1 =em.createQuery(" update CandidateappeartoadvtnumberEntity 
            cnd set cnd.paymentstatus='Completed', cnd.depositedfee=:depofee where
            cnd.studentmasterid=:masterid and cnd.advertisementcode=:advcode");
            String masterId1= updateParam.getMasterId();
            String advCode1=updateParam.getAdvCode();

            query1.setParameter("depofee",amountPaid1);
            query1.setParameter("masterid",masterId1);
            query1.setParameter("advcode",advCode1)
            .executeUpdate();

            em.persist(challanEntity);
            em.flush();
        }
        catch (Exception e){
            logger.info("update error " +e);
            logger.info(e.getMessage());
            return 0;

        }
        return 1 ;
    }

    }

服务类

    @Service
    public class UpdatePaymentServiceImpl implements UpdatePaymentService {

    @Autowired
    UpdatePayment updatePayment;

    @Transactional
    public PaymentResponse getFcgoApiResponse(FcgoUpdateParam updateParam) {
        return updatePayment.getFcgoApiResponse(updateParam);
    }

    }

的applicationContext.xml

    <bean id="entityManagerFactory" class="org.springframework.
    orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.psc" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.
            HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">
                org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
   </bean>
   <bean id="transactionManager" 
    class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" 
        ref="entityManagerFactory" />
    </bean>

1 个答案:

答案 0 :(得分:2)

如果从Transactional方法抛出异常,事务将回滚。

自动回滚运行时异常。

需要显式配置已检查异常的回滚。

您的Transactional方法永远不会抛出异常,因为您捕获了其中的所有异常。所以你需要从catch块中抛出或重新抛出。

Update table
Set comment = ‘configure’
Where product_id is not null and comment_id is not null

Insert into table2(....,....)
Select comment_id, ‘static’
From table
Where not ( product_id is not null and comment_id is not null)

https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back

  

向Spring Framework的事务基础结构指示要转换事务的工作的推荐方法   back是从当前正在执行的代码中抛出一个Exception   事务的上下文。 Spring Framework的事务   基础架构代码将捕获任何未处理的异常,因为它会冒泡   调用堆栈,并确定是否标记   回滚事务。

     

在其默认配置中,Spring Framework的事务   基础结构代码仅标记用于回滚的事务   运行时,未经检查的异常;也就是抛出异常的时候   是RuntimeException的实例或子类。 (错误也会 -   默认情况下 - 导致回滚)。检查抛出的异常   从事务方法不会导致默认回滚   配置。

相关问题