调用delegator.create()前如何校验GenericValue中amount字段类型?
解决方案
获取并校验GenericValue中的amount字段
GenericValue提供两种实用方式来获取字段值并完成类型校验,你可以按需选择:
方式1:直接获取对象并判断类型
使用get()方法拿到字段原始值后,通过instanceof判断是否为BigDecimal:
// 获取amount字段的原始对象 Object amountObj = makeValue.get("amount"); // 校验类型与非空 if (amountObj == null || !(amountObj instanceof BigDecimal)) { // 返回错误给客户端 return ServiceUtil.returnError("参数错误:amount必须为有效数值类型"); }
方式2:利用类型转换方法捕获异常
GenericValue自带getBigDecimal()方法,会尝试将字段值转为BigDecimal,转换失败时抛出GenericEntityException,可捕获异常并返回错误:
try { // 尝试转换为BigDecimal类型 makeValue.getBigDecimal("amount"); } catch (GenericEntityException e) { return ServiceUtil.returnError("amount字段格式无效,请传入正确数值"); }
整合到你的业务代码中
将校验逻辑放在delegator.create()执行之前,完整代码如下:
public static Map<String, Object> createTransaction(Delegator delegator, String caseIds, BigDecimal amountToPay,String createdBy) { String caseId = caseIds.replaceAll(",", ""); GenericValue caseELI = getEntityValue(delegator,"Cases", "caseId", caseId); GenericValue makeValue = delegator.makeValue("AccountTransaction"); Long accountTransactionId = delegator.getNextSeqIdLong("AccountTransaction"); makeValue.put("accountTransactionId", accountTransactionId); makeValue.put("caseId",caseId); makeValue.put("clientId", caseELI.getString("clientId")); makeValue.put("amount",amountToPay); makeValue.put("isCash","Y"); makeValue.put("isPosted","Y"); makeValue.put("createdBy",createdBy); // 校验amount字段类型 Object amountObj = makeValue.get("amount"); if (amountObj == null || !(amountObj instanceof BigDecimal)) { return ServiceUtil.returnError("参数错误:amount必须为BigDecimal类型"); } try { delegator.create(makeValue); } catch(GenericEntityException e){ e.printStackTrace(); return ServiceUtil.returnError("交易创建失败:" + e.getMessage()); } return ServiceUtil.returnSuccess("交易处理成功"); }
补充说明
当前代码中amountToPay本身就是BigDecimal类型,直接存入makeValue不会有类型问题,但如果后续该方法被其他逻辑调用时,amount字段可能被存入非数值类型,这个校验就能提前拦截错误,避免触发数据库异常。
内容的提问来源于stack exchange,提问作者MAXWEL OCHIENG
相关产品推荐
相关产品推荐

