gpt4 book ai didi

java - Spring Jpa @Transactional 不起作用

转载 作者:行者123 更新时间:2023-11-30 02:19:19 25 4
gpt4 key购买 nike

如果一个或多个查询失败,我正在尝试实现事务回滚。所以我在我的服务实现类上注释了@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>

最佳答案

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

运行时异常的回滚是自动的。

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

当您捕获其中的所有异常时,您的事务方法永远不会抛出异常。因此,您需要从 catch block 内抛出或重新抛出。

@Transactional(rollbackFor = MyCustomException.class) // << 
public int updatePayment(FcgoUpdateParam updateParam, String voucherno)
throws Exception{

int a = 5/0; unhandled runtime exception : transaction rolls back

try{
//runtime exception is caught and never rethrown - no rollback
int a = 5/0;
}
catch (Exception e){
// exception in try block re-thrown: transaction rolls back
// throw(e);
}

throw new MyCustomException(); //checked exception rollback only occurs if configured

return 1 ;
}

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

The recommended way to indicate to the Spring Framework’s transaction infrastructure that a transaction’s work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction. The Spring Framework’s transaction infrastructure code will catch any unhandled Exception as it bubbles up the call stack, and make a determination whether to mark the transaction for rollback.

In its default configuration, the Spring Framework’s transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. ( Errors will also - by default - result in a rollback). Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.

关于java - Spring Jpa @Transactional 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47305241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com