Update/Validate data(更新/校验数据)
在Update数据之前,我们往往要对待更新的记录进行有效性的校验,校验级别包括:
Attribute Level Validation :字段级的校验
Entity Level Validation : 记录级的校验
字段级别的校验一般情况下写在EO的set()方法中,根据传入的value来决定是执行setAttributeInternal() 还是throw Exception.(代码应写在setAttributeInternal()之前)
例如你要限制ItemPrice 字段的值不能超过100(当然也可以通过item的属性来设置). 伪码如下:
Public void setItemPrice( Number value)
{
Number maxvalue = new Number(100);
If (value.compareTo(100) >0)
{ throw new Exception(“ Error: Item Price large then 100!”);}
else
{ setAttributeInternal(ITEMPRICE, value);}
}
当校验涉及多个Attribute时,你就不能使用字段级的校验了,需使用记录级的校验,即Entity Level Validation. 此校验在validateEntity()方法中实现.校验代码须写在 super.validateEntity() 之后.
例如如果一个订单的状态为CLOSE, 则不允许更改OrderPrice. 伪码如下:
Public void validateEntity()
{
super.validateEntity();
String status = getOrderStatus();
If (“CLOSE”.equals(status))
{
Number ldorderprice = (Number)getPostedAttribute(ORDERPRICE);
Number neworderprice = (Number)getOrderPrice();
If (oldorderprice.compareto(neworderprice)!=0)
{
throw new Exception(“Error: Order Price can not be edited!”);
}
}
}
备注: getPostedAttribute()方法用来取得字段未修改前的值.
另外, User’s Guide里介绍了多EO之间的校验.这留待后面再研究吧.
不要试图在EO的Validation 里执行rollback() 方法或clearcache() 方法. 当出现校验失败时,有下面两种做法:
Bad Method:
public void validateEntity()
{
….
transaction.rollback()
throw new OAException….
}
Right Method:
public void validateEntity()
{
throw new OAException…
}
In AM Module :
Try
{ transaction.commit();
}
Catch ( OAException ex)
{transaction.rollback();}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10359218/viewspace-677447/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10359218/viewspace-677447/
本文介绍在更新数据前如何进行有效的字段级和记录级校验,包括EO的set()方法及validateEntity()方法的具体应用,并强调正确的异常处理方式。
1346

被折叠的 条评论
为什么被折叠?



