`
lz1365871801
  • 浏览: 21677 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
社区版块
存档分类
最新评论

EBS OAF开发中的Java 实体对象(Entity Object)<二>

 
阅读更多

属性级别的验证

  就像在第三节getEntityState()描述的,不论何时当带有带更新值的页面发出HTTP POST请求时,OAF会把这些值写回到潜在的视图对象,依次通过调用设置器来把这些值写回到潜在的实体对象。因为每个属性的验证应该添加到它的设置器(参考下面示例中ToolBox PurchaseOrderHeaderEOImplsetHeaderId()方法),调用实体对象设置器的过程就会运行属性级别的验证。

   如果你有指定任何声明式的验证(比如,你在JDeveloper Entity Object Wizard中指明了再它被保存之后不有允许被更新),这种验证是在setAttributeInternal()方法中做的,而且这个方法在运行其本身的验证逻辑之后会被调用。也会在validateEntity()里作这类检查。

/**
 * Sets the PO Header Id.
 * Business Rules:
 * Required; cannot be null.
 * Cannot be updated on a committed row.
 */

public void setHeaderId(Number value){
  
  // BC4J validates that this can be updated only on a new line. This
  // adds the additional check of only allowing an update if the value
  // is null to prevent changes while the object is in memory.

  If (getHeaderId() != null){
    throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
                                 getEntityDef().getFullName(), // EO name
                                 getPrimaryKey(), // EO PK
                                 "HeaderId", // Attribute Name
                                 value, // Attribute value
                                 "ICX", // Message product short name
                                 "DEBUG -- need message name"); // Message name
  }

  if (value != null){
    OADBTransaction transaction = (OADBTransaction)getOADBTransaction();
  
    // findByPrimaryKey() is guaranteed to first check the entity cache, then check
    // the database. This is an appropriate use of this method because finding a    
    // match would be the exception rather than the rule so we're not worried 
    // about pulling entities into the middle tier.
    Object[] headerKey = {value};
    EntityDefImpl hdrDef = PurchaseOrderHeaderEOImpl.getDefinitionObject();
    PurchaseOrderHeaderEOImpl hdrEO = 
      (PurchaseOrderHeaderEOImpl)hdrDef.findByPrimaryKey(transaction, new Key(headerKey));

    if (hdrEO != null){
      throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
                                   getEntityDef().getFullName(), // EO name
                                   getPrimaryKey(), // EO PK
                                   "HeaderId", // Attribute Name
                                   value, // Attribute value
                                   "ICX", // Message product short name
                                   "FWK_TBX_T_PO_ID_UNIQUE"); // Message name
    }
  }
  // Executes declarative validation, and finally sets the new value.
  setAttributeInternal(HEADERID, value);
} // end setHeaderId()

 

不同的”设置”方法

   在实体对象内有几种不同的方法来设置值。在代码中,通常调用set<AttributeName>()setAttributeInternal()方法.关于所有可能方法的更多信息请参考Entity Object and View ObjectAttribute Setters

跨属性验证

   实体上包含两个或者更多属性值的所有验证都应该包含在validateEntity()方法中。不要包含任何跨属性验证到当个属性设置器中,因为属性值可能以任意的顺序来设置。

实体验证

  无论什么时候在HTTP POST处理周期中,OAF设置实体对象值,会验证所有它接触的视图对象行,转而会调用相应的实体对象的validateEntity()方法。此外,在提交到数据库之前,实体也会被验证(在组合中直到10次).

   所有在行级别的逻辑-且可以被重复调用的,应该包含在validateEntity()方法中

下面的PurchaseOrderHeaderEOImpl代码演示了典型的实体级别的验证:

 

/**
 * Performs entity-level validation including cross-attribute validation that
 * is not appropriately performed in a single attribute setter.
 */
protected void validateEntity(){
  super.validateEntity();
  // If our supplier value has changed, verify that the order is in an "IN_PROCESS"
  // or "REJECTED" state. Changes to the supplier in any other state are disallowed. 
  // Note that these checks for supplier and site are both performed here
  // because they are doing cross-attribute validation.

  String status = getStatusCode();

  if ((("APPROVED")Equals(status)) || ("COMPLETED"Equals(status))){
    // Start by getting the original value and comparing it to the current
    // value. Changes at this point are invalid.
    Number oldSupplierId = (Number)getPostedAttribute(SUPPLIERID);
    Number currentSupplierId = getSupplierId();

    if (oldSupplierId.compareTo(currentSupplierId) != 0)  {
      throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
                                   getEntityDef().getFullName(), // EO name
                                   getPrimaryKey(), // EO PK
                                   "SupplierId", // Attribute Name
                                   currentSupplierId, // Attribute value
                                   "ICX", // Message product short name
                                   "FWK_TBX_T_PO_SUPPLIER_NOUPDATE"); // Message name
    }

    // If our supplier site has changed, verify that the order is in an "IN_PROCESS"
    // state. Changes to the supplier site in any other state are disallowed.
    Number oldSiteId = (Number)getPostedAttribute(SUPPLIERSITEID);
    Number currentSiteId = getSupplierSiteId();

    if (oldSiteId.compareTo(currentSiteId) != 0){
      throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
                                  getEntityDef().getFullName(), // EO name
                                  getPrimaryKey(), // EO PK
                                  "SupplierId", // Attribute Name
                                  currentSiteId, // Attribute value
                                  "ICX", // Message product short name
                                  "FWK_TBX_T_PO_SUPSITE_NOUPDATE"); // Message name
    }
  } 

  // Verify that our supplier site is valid for the supplier and make sure it is
  // an active "Purchasing" site.
  SupplierEntityExpert supplierExpert = 
    SupplierEOImpl.getSupplierEntityExpert(getOADBTransaction());

  if (!(supplierExpert.isSiteValidForPurchasing(getSupplierId(), getSupplierSiteId()))){
    throw new OAAttrValException(OAException.TYP_ENTITY_OBJECT,
                                 getEntityDef().getFullName(), // EO name
                                 getPrimaryKey(), // EO PK
                                "SupplierSiteId", // Attribute Name
                                 getSupplierSiteId(), // Attribute value
                                 "ICX", // Message product short name
                                 "FWK_TBX_T_PO_SUPSITE_INVALID"); // Message name
  }
} // end validateEntity();

   

跨实体验证

    无论何时在一个实体对象在验证周期中简单调用另一个实体的方法,而开发人员经常认为他们不需要实现“跨实体”验证。在OAF框架中,”跨实体验证”意味非常特别的东西:

l  实体A和实体B在validateEntity()中互相引用(因此实体A需要从实体B中得到一些属性值,且实体B需要从实体A中得到一些属性值).

l  在同一个事物中,你期望两个对象都是”脏”数据(需要验证)…

l  在引用对象取出属性值在它自己的验证中使用之前,其它实体对象是有效的,这很重要。但就有一个时间上的问题就出现了:你想先验证哪一个实体。

小建议:对于组合关系中的主/明细实体对象来说,这不是一个问题,因为通常明细会在父之前验证的,并且BC4J框架实际上会从底部到顶层验证层次到10次直到所有的实体都有效。

从这个非常精确的定义中我们可以看到,需要OAF”跨实体验证”的情况非常稀少。如果你感觉你需要这个,方案涉及要创建一个特殊的实现了BC4J ValidationListener接口的“中间人”对象。简单来说,这个对象决定了应该先验证哪一个对象然后再跨实体验证。参考Advanced Java Entity Object主题中关于这个的示例。

 

不合适的验证失败的处理

   不要尝试在你的实体级别的验证方法(validateEntity(), set<AttribtueName>() 等等).中调用Transaction.rollback(), Transaction.clearEntityCache() or clearCache()做回滚或者清空BC4J缓存。如果你为其它原因需要做这些处理,你必须像下面演示的在AM或者事务级别捕获实体验证异常,并做任何你需要的调用。比如,在AM级别做回滚是安全的。而在实体对象内部做回滚或者清空实体缓存就不是安全的,并可能导致不可预测的行为。

不好的代码:

protected void validateEntity(){
   DBTransaction txn = getDBTransaction();
   // Do not issue a rollback from within the EO.
   txn.rollback();
   throw OAException(...);
}

 好的代码:

 

protected void validateEntity(){
    throw OAException(...);
}

// The following logic is written at theapplication-module level.
try{
   txn.commit();
}catch (OAException e){
   // Cache the exception thrown by thevalidation logic in the EO,
   // and perform the rollback.
   txn.rollback();
}

 

删除

   要删除一个实体对象,调用相应视图对象上的remove()方法,就像下面AM代码示例中演示的。在这个示例中,迭代了一个视图对象的行集来查找匹配的对象来删除.

/**
 * Deletes a purchase order from the PoSimpleSummaryVO using the
 * poHeaderId parameter.
 */
public Boolean delete(String poHeaderId){

  // First, we need to find the selected purchase order in our VO.
  // When we find it, we call remove( ) on the row which in turn
  // calls remove on the associated PurchaseOrderHeaderEOImpl object.
  int poToDelete = Integer.parseInt(poHeaderId);

  OAViewObject vo = getPoSimpleSummaryVO(); 
  PoSimpleSummaryVORowImpl row = null;

  // This tells us the number of rows that have been fetched in the
  // row set, and will not pull additional rows in like some of the
  // other "get count" methods.
  int fetchedRowCount = vo.getFetchedRowCount();
  boolean rowFound = false;

  // We use a separate iterator -- even though we could step through the
  // rows without it -- because we don't want to affect row currency.
  RowSetIterator deleteIter = vo.createRowSetIterator("deleteIter");

  if (fetchedRowCount > 0) 
  { 
    deleteIter.setRangeStart(0); 
    deleteIter.setRangeSize(fetchedRowCount); 
    for (int i = 0; i < fetchedRowCount; i++) { 

      row = (PoSimpleSummaryVORowImpl)deleteIter.getRowAtRangeIndex(i); 
      // For performance reasons, we generate ViewRowImpls for all
      // View Objects. When we need to obtain an attribute value,
      // we use the named accessors instead of a generic String lookup
      // Number primaryKey = (Number)row.getAttribute("HeaderId");

      Number primaryKey = row.getHeaderId();
      if (primaryKey.compareTo(poToDelete) == 0){

        row.remove();
        rowFound = true;
        getTransaction().commit();
        break; // only one possible selected row in this case
      } 
    } 
  }  

  // Always close iterators.
  deleteIter.closeRowSetIterator(); 
  return new Boolean(rowFound);
} // end delete()

 

验证和级联删除

   row.remove()方法转而调用相应实体对象上的remove()方法。要实现任何特殊的删除行为,比如,检查是否允许删除,或者实现级联删除,添加就像下面ToolBox的PurchaseOrderHeaderEOImpl演示的代码到你的实体的remove()方法中。

  注意:因为Oracle EBS编码规则禁止在数据库中使用级联删除,BC4J框架要求为多层次的采购订单业务对象手工实现自己的级联删除。要做到这个,每个实体对象需要在调用super.remove来删除本身之前删除其所有的子对象,就像下面演示的。

/**
 * Marks all the lines for deletion, then mark the header for deletion.
 * You can delete a purchase order only if it is "In Process" or "Rejected."
 */

public void remove(){

  String status = getStatusCode();
  if (("IN_PROCESS"Equals(status)) || ("REJECTED"Equals(status))) {

    // Note this is a good use of the header -> lines association since we
    // want to call remove( ) on each line.
    RowIterator linesIterator = getPurchaseOrderLineEO();
    if (linesIterator != null){

      PurchaseOrderLineEOImpl line = null;
      while (linesIterator.hasNext())
      {
        line = (PurchaseOrderLineEOImpl)linesIterator.next();
        line.remove();
      }
    } 
    super.remove(); // Must be called last in this case.
  }else{

    throw new OARowValException(OARowValException.TYP_ENTITY_OBJECT,
                                getEntityDef().getFullName(),
                                getPrimaryKey(),
                                "ICX", // Message product short name
                                "FWK_TBX_T_PO_NO_DELETE"); // Message name
  }
} // end remove()

 

加锁

BC4J支持下面的加锁技术:

l  悲观锁- 当调用任意setAttribute()方法时,BC4J锁定实体对象的数据库行(特别地,在做任何修改之前)。如果行已经被锁住了,BC4J会抛出一个AlreadyLockedException异常。这是BC4J锁定的默认模式。

l  乐观锁- 在数据库提交处理逻辑过程中,BC4J会锁定实体对象的数据库行。如果行已经被锁定了,BC4J会抛出一个AlreadyLockedException异常。

注意:OAF框架默认使用乐观锁,并且建议你不要违背这个因为连接池不好实现传统的悲观锁。尽管如此,对有丰富”Oracle Forms”开发经验的人员来说,Oracle EBS在基于Forms的应用使用悲观锁。

如果你确认你需要悲观锁,你必须像下面这样改变事务的行为:

// In the application module...
OADBTransaction txn = getOADBTransaction();
txn.setLockingMode(Transaction.LOCK_PESSIMISTIC);

 

过时数据侦测

  当BC4J锁定一行时,它曾是决定是否行已经被另一个用户删除了或者修改了,因为它之前只是被当前用户查询出来。

l  如果行已经被删除了,BC4J会抛出一个RowAlreadyDletedException异常。

l  如果侦测到修改,BC4J会抛出一个RowInconsistentException异常。

对于修改检查,要覆盖默认的一列一列的比较检查行为,需要实体对象属性定义向导中的属性级别Change Indicator标记。如果一个属性的这个指示器被选中了,那么BC4J就局限于这个属性的比较。Oracle EBS PL/SQL API通常使用OBJECT_VERSION_NUMBER表列来决定数据修改,并且这个列也可用于实体对象。参考下面的Object Version Number Column部分.

提交

当你准备提交实体对象的修改,可以简单的在AM中调用getTransaction.Commit()来实现,就像下面的rollback示例中演示的。当你调用这个方法时,你的对象将根据需要进行验证,提交。

  1.commit()方法调用oracle.apps.fnd.framework.OADBTransaction.validate()方法。

  2.validate()方法检查需要验证的根实体对象列表的”验证监听器”。(在多实体组合中,仅根实体对象添加到验证列表)。如果你刚对对象完成验证,但在提交之前,它并不会在验证列表中,因为当对象验证成功时,BC4J会从验证列表中移除它。小建议:如果你想强制进行验证周期,你也可以在你代码的任何地方直接调用OADBTransaction.validate()方法。

   3.假设一个对象存在于验证列表,OADBTransaction.validate()方法会调用实体对象上的finalvalidate()方法,其转而调用validateEntity()方法来调用你的验证逻辑。

注意:BC4J验证列表上的单个实体图的顺序是随机的。但是,在组合业务对象内,比如拥有行和发运的采购订单,BC4J一般在验证父对象之前验证所有的子对象。要达到这个,BC4J仅把组合中的根实体对象放到验证列表中(不包含子对象)。当这个根实体对象调用super.validateEntity,BC4J调用它的子对象的validate方法,然后整个层次都作这样的处理。因为这个原因,你应该通常在调用super.validateEntity方法之后添加你自己的验证来保证在子对象验证完它们本身之后父对象再验证它自己

  4.Commit方法调用了OADBTransaction的postChanges方法。

  5.postChange 方法为那些必须要提交数据到数据库的实体对象列表检查”提交监听器”,

  6.对于提交列表中的所有对象,OADBTransaction的postChnages方法调用实体对象上的postChanges方法。当提交一个对象时,BC4J会从提交列表中移除它。

  7.如果没有错误发生,会发出一个数据库commit并释放所有相应的数据库所。

 

 转自:http://blog.csdn.net/tavor/article/details/19284361

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics