adf常用方法总结

1.使用clientAttribute传值、获取值 或组件上面放客户端属性 

1
2
3
4
5
6
7
8
<af:selectBooleanCheckbox text= ""  label= ""  id= "sbc1"  autoSubmit= "true"   valueChangeListener= "#{viewScope.BulkProcessBean.onSelect}" >
         <af:clientAttribute name= "employeeId"  value= "#{row.EmployeeId}" />
</af:selectBooleanCheckbox>
 
public  void  onSelect(ValueChangeEvent valueChangeEvent) {
          Number id = (Number)valueChangeEvent.getComponent().getAttributes().get( "employeeId" );
...
}

  

注意:客户端属性名不能与其父组件的属性名重复,否则会得到第一个属性名的值,这里的employeeId必须是和selectBooleanCheckbox的属性名不同。
又例: 

1
2
3
4
5
<af:commandButton text= "财务退回"  id= "cb1"  binding= "#{tuiDanBean.eprebateBackBtn}"  action= "#{tuiDanBean.eprebateBack_action}" >
      <af:clientAttribute name= "status"  value= "#{row.Status}" />
</af:commandButton>
//bean中获取属性值
String num =String.valueOf(eprebateBackBtn.getAttributes().get( "status" ));

 

2.为id设置seqence值

1
( new  oracle.jbo.server.SequenceImpl( "employees_seq" ,object.getDBTransaction())).getSequenceNumber()

  


在eo中设置目标属性 勾选表达式 然后编辑值。


3.根据table创建行 并赋值 
1

1
2
3
4
5
6
7
8
CollectionModel _tableModel = (CollectionModel)table.getValue();
JUCtrlHierBinding _adfTableBinding =(JUCtrlHierBinding)_tableModel.getWrappedData();
DCIteratorBinding it = _adfTableBinding.getDCIteratorBinding();
 
oracle.jbo.Row row_adf =  null ; row_adf = it.getNavigatableRowIterator().createRow();
row_adf.setNewRowState(oracle.jbo.Row.STATUS_INITIALIZED);
it.getNavigatableRowIterator().insertRow(row_adf);
row_adf.setAttribute( "DepartmentId" ,row_poi.getCell( 0 ).getNumericCellValue());

  

2

1
2
3
4
5
6
7
8
CollectionModel _tableModel = (CollectionModel)eprebateTable.getValue();
JUCtrlHierBinding _adfTableBinding = (JUCtrlHierBinding)_tableModel.getWrappedData();
DCIteratorBinding it = _adfTableBinding.getDCIteratorBinding();
NavigatableRowIterator iterator = it.getNavigatableRowIterator();
Row row=iterator.createRow();
row.setNewRowState(oracle.jbo.Row.STATUS_NEW);
row.setAttribute( "Num" 4 );
iterator.insertRow(row);

  


3

1
2
3
4
5
6
7
8
9
10
11
import  oracle.binding.BindingContainer;
import  oracle.binding.OperationBinding;
 
BindingContainer bindings = getBindings(); OperationBinding operationBinding = bindings.getOperationBinding( "CreateInsert1" );
operationBinding.execute();
CollectionModel _tableModel = (CollectionModel)eprebateTable.getValue();
JUCtrlHierBinding _adfTableBinding = (JUCtrlHierBinding)_tableModel.getWrappedData();
DCIteratorBinding it = _adfTableBinding.getDCIteratorBinding();
NavigatableRowIterator iterator = it.getNavigatableRowIterator();
Row currentRow = iterator.getCurrentRow();
currentRow.setAttribute( "Num" , iterator.getRowCount());

  

注意:以上三种方式需要在页面中对table进行绑定,第三种还要做操作绑定。


4.得到页面table的迭代器

1
2
3
4
5
6
private  NavigatableRowIterator getTableIter(RichTable table) {
     CollectionModel _tableModel = (CollectionModel) table.getValue();
     JUCtrlHierBinding _adfTableBinding = (JUCtrlHierBinding) _tableModel.getWrappedData();
     DCIteratorBinding it = _adfTableBinding.getDCIteratorBinding();
     return  it.getNavigatableRowIterator();
}

  

1
2
3
4
5
NavigatableRowIterator iterator = getTableIter(vflistTable);
Row currentRow = iterator.getCurrentRow();
currentRow.setAttribute( "Status" 0 );
currentRow.setAttribute( "Isback" "1" );
am.getTransaction().commit();

  

 

5.格式化时间

1
2
3
4
5
6
7
8
9
10
11
12
13
import  java.util.Date;
import  java.text.SimpleDateFormat;
 
SimpleDateFormat sdf =  new  SimpleDateFormat();
sdf.applyPattern( "yyyyMMdd" );
//以上两句可写成
 
SimpleDateFormat sdf =  new  SimpleDateFormat( "yyyyMMdd" );
Date date =  new  Date();
String second = sdf.format(date);
//如果还要时分秒: HH:mm:ss
//注意:如果是时间类是oracle.jbo.domain.Date用
sdf.format(currDate.dateValue())

 

6.必填 必选 
<af:outputLabel value="*" inlineStyle="color:Red;"/>

showRequired="true" 显示蓝色星号 不填没有错误信息 加上 
autocommit=true 不填有错误信息 
required="true" 显示蓝色星号 不填有错误信息 
requiredMessageDetail="没钱不干活啊" 显示错误信息

 

7.下面的程序使用param隐含对象来取得使用者输入的参数以及一些 
jsf基础知识: 

复制代码
    <html>
        <head>
            <title></title>
        </head>
        <body>
            <view>
                <b>您好,
                    <outputText value="#{param.name}"/></b>
            </view>
        </body>
    </html>
复制代码

 

param是JSF-EL预设的隐含对象变量它代表request所有参数的集合,实际是一个java.util.Map型态对象,JSF所提供的隐含对象,大致上对应于JSP隐含物件不过JSF隐含

对象移除了pageScope与 pageContext,而增加了facesContext与view它们分别对应于javax.faces.context.FacesContext与 javax.faces.component.UIViewRoot。

对于Map型态对象,我们可以使用 '.' 运算子指定key值来取出对应的value也可以使用 [ ] 来指定,例如:

     <f:view>
            <b>您好,
                <outputText value="#{param['name']}"/></b>
        </f:view>

在 [ ] 之间也可以放置其它的变量值,例如:

1  <f:view>
2             <outputText value="#{someBean.someMap[user.name]}"/>
3         </f:view>


如果变量是List型态或数组的话,则可以在 [] 中指定索引,例如:

1         <f:view>
2             <outputText value="#{someBean.someList[0]}"/>
3             <outputText value="#{someBean.someArray[1]}"/>
4             <outputText value="#{someBean.someListOrArray[user.age]}"/>
5         </f:view>


您也可以指定字面常数,对于true、false、字符串、数字,JSF EL会尝试进行转换,例如:

<h:outputText value="#{true}"/> 
<h:outputText value="#{'This is a test'}"/> 


如果要输出字符串 必须以单引号 ' 或双自变量 " 括住,如此才不会被认为是变量名称。

在宣告变量名称时 要留意不可与JSF的保留字或关键词同名,例如 :
不可取以下这些名称

true false null div mod and or not eq ne lt gt le ge instanceof empty 
2

<h:outputText value="#{user.date}"> 
    <f:convertDateTime pattern="dd/MM/yyyy"/> 
</h:outputText> 

 


3

复制代码
 1 <html>
 2     <head>
 3         <title>验证器示范</title>
 4     </head>
 5     <body>
 6         <view>
 7             <messages layout="table" style="color:red"/>
 8             <form>
 9                 <h3>请输入您的名称</h3>
10                 <outputText value="#{user.errMessage}"/>
11                 <p>
12                     名称: 
13                     <inputText value="#{user.name}" required="true"/>
14                     <p>
15                         密码: 
16                         <inputSecret value="#{user.password}" required="true">
17                             <validateLength minimum="6"/>
18                         </inputSecret>
19                         <p>
20                             <commandButton value="送出" action="#{user.verify}"/>
21                         </p>
22                     </p>
23                 </p>
24             </form>
25         </view>
26     </body>
27 </html> 
复制代码

 


在<h:inputText>、</h:inputSecret>中我们设定了required属性为 true这表示这个字段一定要输入值我们也在</h:inputSecret>设定了<f: validateLength>,并设定其minimum属性为6,

这表示这个字 段最少需要6个字符。这一次在错误讯息的显示上 我们使用<h:messages>标签,当有验证错误发生时 相关的错误讯息会收集起来 使用<h:messages>卷标可以一次将所有的错误讯息显示出来。

4

<h:commandButton value="送出" action="#{user.outcome}"> 
   <f:actionListener type="onlyfun.caterpillar.LogHandler"/> 
   <f:actionListener type="onlyfun.caterpillar.VerifyHandler"/> 
</h:commandButton> 

5
outputFormat 
产生指定的文字讯息 可以搭配<f:param>来设定讯息的参数以格式化文字讯, 例如

<f:loadBundle basename="messages" var="msgs"/> 
  <h:outputFormat value="#{msgs.welcomeText}"> 
  <f:param value="Hello"/> 
  <f:param value="Guest"/> 
</h:outputFormat> 

 


如果您的messages.properties包括以下的内容

welcomeText={0}, Your name is {1}. 则{0}与{1}会被取代为<f:param>设定的文字 最后显示的文字会是

Hello, Your name is Guest. 
另一个使用的方法则是

<h:outputFormat value="{0}, Your name is {1}."> 
   <f:param value="Hello"/> 
   <f:param value="Guest"/> 
</h:outputFormat> 

 


6
inputSecret 
显示密码输入字段 即输出<input> HTML卷标 其type属性设定为 
password 例如

<h:inputSecret value="#{user.password}"/> 
您可以设定redisplay属性以决定是否要显示密码字段的值 预设是 
false。

inputHidden 
隐藏字段 即输出<input> HTML卷标 其type属性设定为hidden 
隐藏字段的值用于保留一些讯息于客户端 以在下一次发送窗体时一并 
送出 例如 
<h:inputHidden value="#{user.hiddenInfo}"/>


7
如果搭配<f:param>来使用则所设定的参数会被当作请求参数一并送出,例如

<h:commandLink> 
  <h:outputText value="welcome"/> 
  <f:param name="locale" value="zh_TW"/> 
</h:commandLink>

 


8.从数据库中拿数据 
vo.setWhereCluse() 
executeQuery 
AdfFacesContext.getCurrentInstance.addPerttrigger(table)


9.ADF的scope获取方式 

复制代码
        ADFContext.getCurrent().getApplicationScope(); 
        ADFContext.getCurrent().getSessionScope(); 
        AdfFacesContext.getCurrentInstance().getPageFlowScope();

        ADFContext.getCurrent().getRequestScope(); 
        ADFContext.getCurrent().getViewScope();


        Map<String, Object> applicationScope = ADFContext.getCurrent().getApplicationScope();

        Map sessionScope = ADFContext.getCurrent().getSessionScope();

        Map<String, Object> flowScope = AdfFacesContext.getCurrentInstance().getPageFlowScope();

        Map<String, Object> map = AdfFacesContext.getCurrentInstance().getViewScope();

        Map requestScope = ADFContext.getCurrent().getRequestScope();

        Map<String, Object> scope = ADFContext.getCurrent().getViewScope(); 
    }
复制代码

 


10.JSF布局排版两个组件,<h:panelGrid>、<h:panelGroup> 
<h:panelGrid> 这个卷标可以用来作简单的组件排版,它会使用HTML表格卷标来绘制表格,并将组件置于其中,主要指定columns属性,如设定为 2

复制代码
<h:panelGrid columns="2"> 
   <h:outputText value="Username"/> 
   <h:inputText id="name" value="#{userBean.name}"/> 
   <h:outputText value="Password"/> 
   <h:inputText id="password" value="#{userBean.password}"/> 
   <h:commandButton value="submit" action="login"/> 
   <h:commandButton value="reset" type="reset"/> 
</h:panelGrid> 
复制代码

 


则自动将组件分作 2 个 column来排列,注意 <h:panelGrid>的本体间只能包括JSF组件,如果想要放入非JSF组件,例如简单的样版,emplate,文字,则要使 <f:verbatim>包括住,例如 

复制代码
<h:panelGrid columns="2"> 
   <f:verbatim>Username</f:verbatim> 
   <h:inputText id="name" value="#{userBean.name}"/> 
   <f:verbatim>Password</f:verbatim> 
   <h:inputText id="password" value="#{userBean.password}"/> 
   <h:commandButton value="submit" action="login"/> 
   <h:commandButton value="reset" type="reset"/>
 </h:panelGrid>
复制代码

 

 

这个组件用来将数个JSF组件包装起来使其看来像是一个组件例 
如

复制代码
<h:panelGrid columns="2"> 
   <h:outputText value="Username"/> 
   <h:inputText id="name" value="#{userBean.name}"/> 
   <h:outputText value="Password"/> 
   <h:inputText id="password" value="#{userBean.password}"/> 
   <h:panelGroup> 
      <h:commandButton value="submit" action="login"/> 
      <h:commandButton value="reset" type="reset"/> 
   </h:panelGroup> 
</h:panelGrid>
复制代码

 


11.为table中的字段添加排序、过滤 
<af:column 
headerText="#{bindings.CdsExportEprebateView2.hints.Vfno.label}" 
id="c1" filterable="true" sortable="true" sortProperty="Vfno"> 
<af:outputText value="#{row.Vfno}" 
id="ot2"/> 
</af:column> 
只读的字段生成之后不能排序不能过滤这时候需要加上几个属性 
filterable="true" sortable="true" sortProperty="Vfno" 
-------------------------------------------------------------------- 
12.在vo上增加条件查询并应用条件查询 
条件查询名字filterByDept 
条件查询条件( (Employees.DEPARTMENT_ID = :deptId ) ) 
应用条件查询 
public void applyEmplyeeCriteria(Integer deptId){ 
ViewObjectImpl employees = 
(ViewObjectImpl)findViewObject("Employees"); 
employees.setApplyViewCriteriaNames(null); 
ViewCriteria criteria = 
employees.getViewCriteria("filterByDept"); 
employees.applyViewCriteria(criteria); 
employees.ensureVariableManager().setVariableValue("deptId", 
deptId); 
employees.executeQuery(); 
} ------------------------------------------------------------------- 
13.弹出消息框 
import javax.faces.application.FacesMessage; 
import javax.faces.context.FacesContext;

public static void popupMessage(String level,String detail){ 
FacesMessage fm = new FacesMessage(null,detail);//默认级别 
为info 
if("info".equals(level)) 
fm.setSeverity(fm.SEVERITY_INFO); 
else if("warn".equals(level)) 
fm.setSeverity(fm.SEVERITY_WARN); 
else if("error".equals(level)) 
fm.setSeverity(fm.SEVERITY_ERROR); 
else if("fatal".equals(fm.SEVERITY_FATAL)) 
fm.setSeverity(fm.SEVERITY_FATAL); 
FacesContext.getCurrentInstance().addMessage(null, fm); 

------------------------------------------------------------- 
14.行拷贝 代码中进行row copy 
//将one里的某些字段值copy给currentRow 
private void setApplyAttribute(Row currentRow,Row one,String...columns){ 
//不要空指针 
if(currentRow==null || one==null || columns.length==0) 
return; 
//循环赋值 
for(String s:columns) 
if(one.getAttribute(s)!=null) 
currentRow.setAttribute(s, one.getAttribute(s)); 

---------------------------------------------------------- 
15.页面三目表达式判断形式 
#{(row.Datastate eq '0') ? '正常':((row.Datastate eq '1') ? '暂存':'删除')}

inlineStyle="background-color:#{(row.Canmerge == '1')? ((row.Ismother == '0')? 'yellow' : ''):''};"readOnly="#{bindings.Marginal!=null}" 

---------------------------------------------------------

16.安全验证重定向到另一个URL 
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext(); 
HttpServletResponse response = (HttpServletResponse)ectx.getResponse(); 
String url = ectx.getRequestContextPath()+”/adfAuthentication?logout=true&am p;end_url=/faces/start.jspx”; 
try { 
response.sendRedirect(url); 
} catch (Exception ex) { 
ex.printStackTrace(); 

--------------------------------------------------------- 
17.刷新控件PPR
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent); 
--------------------------------------------------------- 
18.查找控件 
private UIComponent getUIComponent(String name) { 
FacesContext facesCtx = FacesContext.getCurrentInstance(); 
return facesCtx.getViewRoot().findComponent(name) ; 

---------------------------------------------------------

19.获取table选中的行(不一定是当前行) 
RowKeySet selection = resultTable.getSelectedRowKeys(); 
Object[] keys = selection.toArray(); 
List receivers = new ArrayList(keys.length); 
for ( Object key : keys ) { 
User user = modelFriends.get((Integer)key); 

// 获取table选中的行的另一种 
for (Object facesRowKey : table.getSelectedRowKeys()) { 
table.setRowKey(facesRowKey); 
Object o = table.getRowData(); 
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o; 
Row row = rowData.getRow(); 
Test testRow = (Test)((DCDataRow)row).getDataProvider() ; 

------------------------------------------------------------------ 
20.在eo实现类中 这个好搞个方法验证 
public boolean validateLength(Number length) { 
if(length!=null && String.valueOf(length).contains(".")) 
return false; 
return true; 
} ------------------------------------------------------------------ 
21.应用条件查询并设置参数值 
public void applyJobCriteria(String title){ 
ViewObjectImpl employees = 
(ViewObjectImpl)this.getJobsView1(); 
employees.setApplyViewCriteriaNames(null); 
ViewCriteria criteria = 
employees.getViewCriteria("JobsViewCriteria"); 
employees.applyViewCriteria(criteria); 
employees.ensureVariableManager().setVariableValue("titleVar", 
title); 
employees.executeQuery(); 
employees.setApplyViewCriteriaNames(null); 

--------------------------------------------------------------- 
22.开发人员可以通过继承javax.faces.event包中PhaseListener接口实 
现阶段listener这个接口定义了3个方法

PhaseId getPhaseId() 
void afterPhase(PhaseEvent) 
void beforePhase(PhaseEvent)

getPhaseId方法返回何时提交阶段事件到listener在不指定阶段的情 
况下阶段listener的beforePhase和afterPhase方法将在每个生命周 
期中调用6次即每个生命周期阶段调用一次。 
但是上面这样不指定生命周期阶段的用法通常情况下是不合理的如果 
不指定阶段则意味着所有阶段都会执行代码在实际的应用中不太可能 
需要这样

而如果你的逻辑处理需要花费很长时间的话由于错误的使用可能导致 
页面显示的严重性能问题因此在往beforePhase和afterPhase方法中 
添加业务逻辑时

需要明确根据阶段来执行明确指定在哪个阶段执行代码


public class CustomPhase implements PhaseListener {

public void beforePhase(PhaseEvent e) { 
if(e.getPhaseId == PhaseId.INVOKE_APPLICATION) { 
System.out.println("BEFORE " + e.getPhaseId()); 


public void afterPhase(PhaseEvent e) { 
if(e.getPhaseId == PhaseId.INVOKE_APPLICATION) { 
System.out.println("AFTER " + e.getPhaseId()); 



------------------------ 
23.页面定义js的两种方法 
<af:document> 
<af:resource type="javascript" source="/customJsCode.js"/> 
… 
</af:document>

<af:document> 
<af:resource type="javascript"> 
function customJsFunction(){ … } 
</af:resource> 
… 
</af:document> 
-------------------------- 
24.页面传参 js调用 <af:clientAttribute name="rowKey" 
value="#{row.rowKeyStr}"/> 
<af:clientListener method="handleDepartmentClick" 
type="click"/>

<af:document> 
<af:messages/> 
<f:facet name="metaContainer"> 
<af:group> 
<script> 
function handleDepartmentClick(evt){ 
rowKey = evt.getSource().getProperty("rowKey"); 
alert(rowKey); 

</script> 
</af:group> 
</f:facet> 
... 
</af:document> 
----------------------------- 
25.正则表达式验证 
<af:validateRegExp pattern="[^.]*" hint="提示" messageDetailNoMatch="必须输入整数"/>

---------------------------- 
26. 
安全退出 注销 
FacesContext fctx = FacesContext.getCurrentInstance(); 
ExternalContext ectx = fctx.getExternalContext(); 
String url = ectx.getRequestContextPath() + 
"/adfAuthentication?logout=true&end_url=/faces/Home.jsp 
x"; 
try { 
ectx.redirect(url); 
} catch (IOException e) { 
e.printStackTrace(); 

fctx.responseComplete(); 
return null; 
----------------------------------------------- 
27.ADF中怎样获取访问web.xml中的参数值 
web.xml中的参数值可以提供给应用一些特殊的配置信息 
How-to read context parameters in web.xml from ADF? 
Context parameters in web.xml can be used to provide application specific configurations to ADF. To 
access context parameters in ADF, you use the FacesContext static 
context class as shown below

FacesContext fctx = FacesContext.getCurrentInstance(); 
ExternalContext ectx = fctx.getExternalContext(); 
ServletContext servletContext = (ServletContext) ectx.getContext(); 
String myContextParam = 
(String)servletContext.getInitParameter("mycontextparam");

------------------------------------------------- 
28.this.getDBTransaction().postChanges() 
//也让它从缓存中查询满足条件的记录 但是这个会有一些操作上的隐 
患 
------------------------------------------------- 
29.Row 、Number 的api位置 
import oracle.jbo.Row; 
import oracle.jbo.domain.Number; 
------------------------------------- 
30.创建一条有外键link的记录 需要先拿到主表的row然后create

1
2
3
4
5
//创建一条对应的eta记录
ViewRowSetImpl vrsi=(ViewRowSetImpl)row.getAttribute( "CdsExportEtaView" );
Row etaRow = vrsi.createRow();
vrsi.insertRow(etaRow);
am.getDBTransaction().commit();

  


--------------------------------- 
31.从请求中获取url信息 
request.getHeader("Host")--->127.0.0.1:7101 
request.getContextPath()--->/cds 
request.getServletPath()--->/faces 
------------------------------ 
32.写入文件

1
2
3
4
5
6
InputStream inputStream= new  FileInputStream(file);
InputStreamReader isr= new  InputStreamReader(inputStream, "UTF-8" );
BufferedReader br= new  BufferedReader(isr);
String str;
while ((str=br.readLine())!= null )
out.write(str.getBytes( "UTF-8" ));



33.得到某个迭代器的当前行的某个属性值

1
2
3
4
5
private  Object getCurrExportid(){
    DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
    DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get( "CDS_Export_APPLY_ETA1Iterator" );
    return  iterBind.getCurrentRow().getAttribute( "Exportid" );
}

  


------------------------------------- 
34.得到用户名 安全 

1
String user = ADFContext.getCurrent().getSecurityContext().getUserName();

  

 

How-to access the username from ADF BC? 
To access the username of an authenticated web session in ADF 
Business Components, use the security 
context as shown below 

1
2
ADFContext adfctx = ADFContext.getCurrent();
String user = adfctx.getSecurityContext().getUserPrincipal().getName();

  

The security context is also accessible from Groovy in ADF Business Components, for example to define 
a bind variable used in a View Criteria that queries View Object data in 
the context of the authenticated user 

adf.context.securityContext.userName

The SecurityContext is not available in Oracle JDeveloper releases 
before 11g. In older releases, the 
authenticated username is accessible from a call to 
getUserPrincipalName() on the Application Module 
Impl class. This "old" API is still supported but discouraged in favor of 
the SecurityContext accessed 
from the ADF context. 
------------------------------ 
35.outputLabel和outputText两者有何不同
outputLabel 文字有颜色,重在label作用 
outputText 文字一般,不重在label作用 
<af:outputLabel value="税名称" id="ol4"/> 
<af:outputText value="#{bindings.Tariffcds.inputValue}" id="ot84"/>

36.vo 增加临时属性 
因战斗需要 在vo中新增临时属性ligangcolor 设置:
type:String 
value type:expression 
value
关键是value的取值 有两种来源 一种是其他字段的处理值 还有一 种就是自定义值。 
自定义值支持Java语言 貌似是groovy语言吧 不确定 以下两种设 
值方式是都是正确的 
1 "blue" 
2 new String("blue") 
这种设置初始值的方式 发现有一个缺点就是页面第一次加载会卡。 
--------------------------------------------------- 
37.对于一些基本的CUD操作 可以弄个公共方法: 
import oracle.adf.model.BindingContext; 
import oracle.binding.BindingContainer; 
import oracle.binding.OperationBinding; 
/* 
*opr操作如delete、commit等 
*return操作成功返回true否则返回false 
*/ 
private boolean opr_action(String opr){ BindingContainer bindings = 
BindingContext.getCurrent().getCurrentBindingsEntry();; 
OperationBinding opr = bindings.getOperationBinding(opr); 
opr.execute(); 
if(!delete.getErrors().isEmpty()){ 
System.out.println("删除失败"); 
return false; 
}else 
return true; 

-------------------------------------- 
38.在Managed Bean中给ADF RichTable排序 . 
1Backing Bean中设置排序方法 
public void sortMethod(SortEvent event){ 
DCIteratorBinding iter = ADFUtils.findIterator("xxxxVOIterator"); 
String propery = event.getSortCriteria().get(0).getProperty(); 
String isAsending = event.getSortCriteria().get(0).isAscending() 
== true ? "asc" : "desc"; 
//在内存中排序 
ViewObject vo = iter.getViewObject(); 
vo.setSortBy(propery + " " + isAsending); 
vo.setQueryMode(ViewObject.QUERY_MODE_SCAN_VIEW_ROWS); vo.executeQuery(); 
vo.setSortBy(null); //去除排序基准 
SortCriteria[] sc = new SortCriteria[0]; 
iter.applySortCriteria(sc); 
}

2在RichTable中添加sort listener事件 
<af:table ..... 
sortListener="#{backing_xxx.sortMethod}"

提示 如果是table中字段的默认升降序排序 可以在dataBingding中 
设置各个字段的排序方式。 
---------------------------------- 
39.js运行.exe 
function RunExe() 

var commandtoRun = "C:\\file.exe"; 
var objShell = new 
<strong>ActiveXObject</strong>("Shell.Application"); 
objShell.<strong>ShellExecute</strong>(commandtoRun, "", "", 
"open", 1); 

-------------------------------- 
40.弹出消息框 
private void popupMessage(String summary,String detail){ 
FacesMessage fm = new FacesMessage(); 
fm.setSeverity(fm.SEVERITY_WARN); 
fm.setSummary(summary); 
fm.setDetail(detail); 
FacesContext.getCurrentInstance().addMessage(null, fm); 

注意以上是弹出消息框的完整代码已经被收入JSFUtils工具类中 
所以你可以简单使用以下 
JSFUtils.addFacesInformationMessage("这是一个一般信息提示框。"); 
JSFUtils.addFacesErrorMessage("这是一个错误信息提示框。"); 
-------------------------------- 
41.交通灯示例代码 
<af:column sortProperty="Exc" 
filterable="true" 
sortable="true" 
headerText="#{bindings.CdsImportView 
View1.hints.Exc.label}" 
id="c1"> <dvt:gauge gaugeType="LED" 
ledStyle="LS_DOT" 
imageHeight="24" 
imageWidth="24" 
rendered="true" 
textAntialiasing="false" 
visualEffects="NONE" 
gaugeSetDirection="GSD_DOWN" 
thresholdDialStyle="TDS_RING_FILL 

animationOnDataChange="none" 
animationIndicators="NONE" 
renderImagemap="false" 
flashDefaultFontLoading="FLASH_DE 
FAULT_FONT_LOADING_NONE" 
partialSubmit="false" 
imageFormat="PNG_STAMPED" 
inlineStyle="height:30px;" 
value="#{row.Exc}" 
svgFontEmbedding="SVG_FONT_EM 
BEDDING_NONE" 
graphicAntialiasing="false" specularHighlight="SH_OFF" 
id="g2"> 
<dvt:topLabel position="LP_NONE"/> 
<dvt:thresholdSet> 
<dvt:threshold text="Low" 
thresholdMaxValue="1" 
fillColor="#ff0000"/> 
<dvt:threshold text="Medium" 
thresholdMaxValue="2" 
fillColor="#00ff00"/> 
<dvt:threshold text="High" 
fillColor="#00ff00"/> 
</dvt:thresholdSet> 
</dvt:gauge> 
</af:column> 
--------------------------------------------------- 
42.可以把批处理、复选框批量选中代码抽象出来 示例代码如下 
1页面代码 
<af:column id="c470" headerText="选择校验" 
align="center" width="50"> 
<af:selectBooleanCheckbox text="" label="" 
id="sbc1" autoSubmit="true" valueChangeListener="#{impCos 
tBean.selectHandler}"> 
<af:clientAttribute name="costId" value="#{row.Id}"/> 
</af:selectBooleanCheckbox> 
</af:column> 
2impCostBean中 
//得到保存选中的list 
public List<Number> getSelectList(){ 
Map viewScope = ADFContext.getCurrent().getViewScope(); 
Object obj = viewScope.get("isSureSelectList"); 
if(obj==null){ 
obj=new ArrayList<Number>(); 
viewScope.put("isSureSelectList", obj); 

return (List<Number>)obj; 

//选中、退选处理 
public void selectHandler(ValueChangeEvent valueChangeEvent) { 
// Add event code here... 
System.out.println("old 
value:"+valueChangeEvent.getOldValue()); 
System.out.println("new value:"+valueChangeEvent.getNewValue()); 
Boolean old = (Boolean)valueChangeEvent.getOldValue(); 
Boolean newValue = 
(Boolean)valueChangeEvent.getNewValue(); 
//排除这一情况null-->false 
if (old == null && newValue.booleanValue() == false) 
return; 
Number id 
=(Number)valueChangeEvent.getComponent().getAttributes().get("c 
ostId"); 
if (!newValue.booleanValue()) { 
if (getSelectList().contains(id)) { 
System.out.println("放弃选择:"+id); 
getSelectList().remove(id); 

} else { 
System.out.println("选择:"+id); 
getSelectList().add(id); 

System.out.println("当前选择个数"+getSelectList().size()); 


以上不同页面之间可以共用啊 
以下是业务处理示例 
处理1 
//更新选择的费用记录的确定标志 
public String sureHandler_action() { 
List<Number> costIdList = getSelectList(); 
//1 检查如果用户什么都没选 
if(costIdList==null || costIdList.size()==0) 
return null; 
//2 检查通过迭代处理 
for(Number costId:getSelectList()){ 
... 

//3 提交保存 
BindingContainer bindings = getBindings(); 
OperationBinding operationBinding = 
bindings.getOperationBinding("Commit"); 
operationBinding.execute(); 
return null; 

处理2 //cost 迭代更新cost的确定标志位 
public void updateSureFlag(String voName,List<Number> 
costIdList){ 
//先检查参数 
if(voName==null || "".equals(voName) || costIdList==null || 
costIdList.size()==0) 
return; 
//迭代更新 
ViewObjectImpl vo = 
(ViewObjectImpl)findViewObject(voName); 
for(Number costId:costIdList){ 
Row[] byKey = vo.findByKey(new Key(new Object[] 
{ costId }), 1); 
if (byKey != null && byKey.length>0){ 
Row row=byKey[0]; 
row.setAttribute("Issure", '1'); 


this.getDBTransaction().commit(); 

------------------------------------------------------------ 
43.根据条件变颜色、底色三目表达式的运用 inlineStyle="background-color:#{(row.Canmerge == '1')? 
((row.Ismother == '0')? 'yellow' : ''):''};" 
----------------------------------------------------------- 
44.自定义窗体弹出的两种方式 
popup 
1页面使用showPopupBehavior 
<af:outputText value="outputText2" id="ot1"> 
<af:showPopupBehavior triggerType="mouseOver" 
popupId="p2s" 
align="afterStart"/> 
</af:outputText> 
<af:popup id="p2s"> 
<af:noteWindow id="wnw21" > 
<f:verbatim>maoinmimewoovowvwvvowvm 
sftrgregf</f:verbatim> 
</af:noteWindow> 
</af:popup> 
2代码 需要绑定popup到bean中 
RichPopup onPopup = this.getOnPopup(); 
RichPopup.PopupHints hints = new RichPopup.PopupHints(); 
onPopup.show(hints); 
------------------------------------------------------- 45.根据主键找记录 
ViewObject vo= this.getCdsUserView1(); 
Row[] byKey = vo.findByKey(new Key(new Object[] 
{ costId }), 1); 
if (byKey != null && byKey.length>0){ 
Row row=byKey[0]; 
for(String key:attrNames.keySet()) 
System.out.println(key+":"+row.getAttribute(key)); 

-------------------------------------------------------- 
46.组件相关 
(1)通过组件上的事件获取组件 
FacesContext context = FacesContext.getCurrentInstance(); 
FacesMessage messagge = new FacesMessage("Successfully 
uploaded file"+file.getFilename()+"("+file.getLength()+"bytes)"); 
context.addMessage(event.getComponent().getClientId(context),mes 
sage); 
(2)获取根组件 
public static void addFacesErrorMessage(String attrName, String 
msg){ 
FacesContext ctx = FacesContext.getCurrentInstance(); 
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, attrName, msg); 
ctx.addMessage(JSFUtils.getRootViewComponentId(), fm); 

(3)通过根组件+组件ID查找组件 
pubic static void addFacesErrorMessage(String attrName, String 
msg){ 
FacesContext ctx = FacesContext.getCurrentInstance(); 
FacesMessage fm = new 
FacesMessage(FacesMessage.SEVERITY_ERROR, attrName, msg); 
ctx.addMessage(JSFUtils.getRootViewComponentId().findCompone 
nt("productpriceIT").getClientId(ctx), fm); 

------------------------------------------------------ 
47.LOV页面使用 
1拖放view至页面 选择生成ADF Form 发现JobId的显示组件 
自动设置为ADF List of Values Input。如果选中Query List Automatically 
弹出查询页面时 会直接显示所有结果。 
JobId为一个文本输入框 旁边有一个查询按钮 点击后可以查询 选 
择一条记录 会返回到文本输入框。注意 无论查询显示的是哪些字段 
返回的都是 JobId。 
2设置inputListOfValues组件的autoSubmit="true"。除了(3)的运 
行效果之外 . 当输入AD_ 按下Tab键 会弹出所有以AD_开头的JobId选项。 
. 当输入AD_V 按下Tab键 会直接补全为AD_VP 因为只有一个值 
满足条件。 
3为inputListOfValues组件增加autoSuggestBehavior 如 
<af:autoSuggestBehavior 
suggestedItems="#{bindings.JobId.suggestedItems}"/>此时 除了(4) 
的运 行效果之外 会新增一种效果 随着用户的输入 会自动下拉 
显示匹配的结果。经过测试 中文也可以支持自动匹配。 
----------------------------------------------------- 
48.添加表格的excel导出和打印功能 
<f:facet name="menus"> 
<af:menu text="报表制作"> 
<af:commandMenuItem text="导出EXCEL"> 
<af:exportCollectionActionListener type="excelHTML" 
exportedId="t1"/> 
</af:commandMenuItem> 
<af:commandMenuItem text="打印"> 
<af:showPrintablePageBehavior/> 
</af:commandMenuItem> 
</af:menu> 
</f:facet> 
----------------------------------------------------- 49.下拉列表的情况 
Consignee==》null value 
Consignee1==》0 索引 
Transportation==》出口海运 value 
Transportation1==》13 索引 
Portofloading==》SHANGHAI value 
Portofloading1==》114 索引 
Pickupaddress==》5662 value 
Pickupaddress1==》2 索引 
货代公司Forward==> Schenker value 
货代公司Forward1==> 4 索引

使用值变事件得到下拉列表的值时发现不能使用 
ADFUtils.getBoundAttribute("");这个只能获取值变前的值。 
--------------------------------------------------- 
50.bean中得到当前行的高级使用 
效果 点击某个按钮后传入选中行的整个对象 
方法 为该按钮添加setActionListener其from值绑定到Table对应 
iterator的currentRowto值绑定到页面对应MB中ViewRowImpl类型 
的变量rowObject(该变量就是用来接收传进来的行对象的)。实例 
<af:setActionListener from="#{bindings.tableIterator.currentRow}" 
to="#{MB.rowObject}">,然后在rowObject的set方法中就可以设置行中字段值了。 
-------------------------------------------------------- 
51.类oracle.jbo.server.ApplicationModuleImpl的一些方法 
1executeCommand 
public int executeCommand(java.lang.String command) 
用于在服务器端执行特别的sql语句。返回值说明执行这条sql影响的 
行数。该方法适用于测试和调试应用。 
Specifies a valid SQL statement to be executed by the server. The 
return integer value describes how many rows were affected by the 
SQL statement. This is a utility method for testing and debugging 
queries and applications. 
The following code example uses executeCommand. The SQL string is 
designed to update the EMP table. This example passes the string to 
executeCommand, then prints a message to report how many rows 
were actually updated.

public static void demoUpdateColumn(ApplicationModule appMod) { 
String sqlStr = "UPDATE EMP " + 
"SET MGR=7007 " + 
"WHERE MGR=7698 ";

int n = appMod.getTransaction().executeCommand(sqlStr); System.out.println("Updated " + n + " rows."); 
}

注意 这方法会执行任何可用的sql 比如说删除数据库中的一张表。 
比较危险 慎用。 
Be careful when using executeCommand, because it will execute any 
valid SQL statement. For example, you could perform an operation like 
the following DDL command:

appMod.getTransaction().executeCommand("DROP TABLE 
MYTEMPTABLE");

A pending database transaction could be committed inadvertently due 
to the implicit commit performed by DDL operations, as well as having 
any row locks released.


Parameters: 
command - a valid SQL statement.

-------------------------------------------------------------------------------- 
2getDBTransaction public DBTransaction getDBTransaction() 
得到当前这个am的事务不同am的事务不共享。 
Gets this Application Module's database transaction. Note that if this 
method is invoked on a nested Application Module, the root 
Application Module's transaction is returned. This is because the 
transaction is shared by all Application Modules contained by the root 
Application Module. 
If the user creates two root Application Modules, they normally do not 
share the transaction. To share a transaction acroos root Application 
Modules, the user would need to define a global transaction through 
JTA and have both Application Modules participate in it.

Returns: 
the transaction. 
Throws: 
java.lang.IllegalStateException - if no root Application Module is found. 
This could happen if the user calls this method on an Application 
Module that has

-------------------------------------------------------------------------------- 
52.实体中的属性之历史属性和可更新的和刷新 
1.History Column 
Select this checkbox to log changes to the database. You can only log 
changes if: You have implemented authorization (login) using 
JAAS/JAZN. The selected attribute is persistent. Changes will be 
logged in the corresponding database column. You have not selected 
Primary Key, Mandatory, or Discriminator. The attribute type is Char, 
Character, String, Date, Timestamp, or Number.

Once you have selected this checkbox, choose the history column type: 
1created on 创建时间 
Select this option to use the column to log the date on which the row 
was first created. The attribute type must be Date or Timestamp. 
2modified on 修改时间 
Select this option to use the column to log the date on which the row 
was last modified. The attribute type must be Date or Timestamp. 
3created by 谁创建的 
Select this option to use the column to log the user who created the 
row. The attribute type must be Char, Character, or String. 
4modified by 谁修改的 
Select this option to use the column to log the user who last modified 
the row. The attribute type must be Char, Character, or String. 
5version number Select this option to use this column to log the number of times the 
row has been changed. The attribute type must be Number.

2.Updateable 
The view attribute setting is based on the entity attribute setting and 
can made more restrictive.

2Always 
Select to make an attribute updatable.

3While New 
Select to make an attribute updatable before an entity is first posted.

4Never 
Select to make an attribute read-only.

3.Refresh After 
Select one or both of these options to reflect the effects of triggers 
after DML operations.

1update 
After the entity object posts changes to an existing database row, the entity object retrieves the value of the attribute from the 
corresponding database field.

2Insert After 
the entity object inserts a new row in the database, the entity object 
retrieves the value of this attribute fromhe corresponding database 
field 
---------------------------------------------------------------- 
53.ADF自带过滤功能不区分大小写敏感不敏感 
caseInsensitive 
caseSensitive

filterFeatures="caseInsensitive" 
例子如下 
<af:column sortProperty="Consignee" filterable="true" 
sortable="true" 
headerText="#{bindings.CdsExportApplyVie 
w1.hints.Consignee.label}" 
id="c35" filterFeatures="caseInsensitive"> 
--------------------------------------------------------------- 
54.将当前行的DepartmentId放入pageFlowScope中; 
CollectionModel model = (CollectionModel) employeeTable.getValue(); 
JUCtrlHierBinding tableBinding = (JUCtrlHierBinding) 
model.getWrappedData(); 
//table synchronizes row selection with current binding row 
DCIteratorBinding tableIterator = 
tableBinding.getDCIteratorBinding(); 
if (tableIterator.getCurrentRow() != null) { 
Object departmentIdValue = 
tableIterator.getCurrentRow().getAttribute("DepartmentI 
d"); 
//copy value into the pageFlowScope, which is returned in an 
task 
//flow param output 
ADFContext adfCtx = ADFContext.getCurrent(); 
Map pageFlowScope = adfCtx.getPageFlowScope(); 
pageFlowScope.put("departmentId", departmentIdValue); 

---------------------------------------------------------------- 
55.玩输出模式 
<af:column id="c201" headerText="操作" 
width="105" 
rendered="#{adfFacesContext.outputMode!='printable'}"> 
<af:commandButton text="财务退回" 
id="cb11" 
binding="#{tuiDanBean.vflistBa 
ckBtn}" 
action="#{tuiDanBean.vflistBac 
k_action}" 
disabled="#{row.Vfdate!=null} 
"/> 
</af:column> 
<af:activeImage source="/images/stockChart.gif" 
rendered="#{adfFacesContext.outputMode != "email"}"/> 
-------------------------------------------------------------- 
56.转向问题看官方最佳解说 
FacesContext context = FacesContext.getCurrentInstance(); 
HttpSession session = 
(HttpSession)context.getExternalContext().getSession(tru 
e);//session不可能为空 
String actionStr = 
String.valueOf(session.getAttribute("firstLink")); 
context.getApplication().getNavigationHandler().handleNavi 
gation(context, null, actionStr); 
How-to efficiently redirect an ADF Faces view using ADFc 
ADF Faces developers use 
facesContex.getExternalContext().redirect(String) to issue a GET 
request to a 
JSF view. Using ADFc, the redirect URL should neither be read from 
the current UIView root directly or 
provided in the form /faces/<viewId name>. Instead, have the 
controller generating the redirect String 
for a specific viewId as shown below: 
FacesContext fctx = FacesContext.getCurrentInstance(); 
ExternalContext ectx = fctx.getExternalContext();

String viewId = "... add viewId...." 
ControllerContext controllerCtx = null; 
controllerCtx = ControllerContext.getInstance(); 
String activityURL = controllerCtx.getGlobalViewActivityURL(viewId); 
try{ 
ectx.redirect(activityURL); 
} catch (IOException e) { 
//Can't redirect 
e.printStackTrace(); }

Why? Because a redirect is a Get request and you don't want ADFc to 
treat it as a new application request 
but instead retrieve the internal controller state. For this you need the 
state toke in the redirect URL, 
which is what the code line above does 
---------------------------------------------------------------- 
57.bean中增加组件 
UIComponent parent =....; 
RichInputText it = new RichInputText();

it.setValue("test...");parent.getChildren().add(it); 
--------------------------------------------------------------- 
58.删除确认对话框 
1popup所在页面位置 
<f:view> 
<af:document id="d1" title="成品计划员管理"> 
<af:messages id="m1"/> 
<af:form id="f1"> 
<!-- 对话框 开始 --> 
<af:popup id="p1"> ... 
2popup示例只需要改这个dialogListener 
<af:popup id="p1"> 
<af:dialog id="d5" title="删除确认" 
dialogListener="#{consigneeBean.deleteApply}"> 
<af:panelGroupLayout id="pg210" halign="center" 
layout="vertical"> 
<br/> 
<af:outputText value="确定要删除吗 " 
id="ot341"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<br/> 
</af:panelGroupLayout> 
</af:dialog> 
</af:popup> 
3调用者 
<af:commandToolbarButton text="删除" id="ctb4"> 
<af:showPopupBehavior triggerType="click" 
popupId=":::p1"/> 
</af:commandToolbarButton> 
------------------------------------------------------------- 
59.常用工具类小结 
1org.apache.commons.lang.math.NumberUtils 处理数字与字符串 
的无异常转化 
例子 
String str=null; 
int i = NumberUtils.toInt(str); 
System.out.println("i="+i); 
字符串是null 或是其他任意不能转化成整数的字符串 都会转变成0。 
2java.text.SimpleDateFormat 用于格式化日期 
3java.text.DecimalFormat 用于格式化数字

--------------------------------------------------------------- 
60.将文件作为流读入内存

        InputStream input = ClassLoaderUtil.getStream("sap.properties");
        prop.load(input);
        input.close();

        InputStream is = InitialLoader.class.getResourceAsStream("/global.properties");


61.点一下按钮关闭当前页面

复制代码
1         FacesContext fc = FacesContext.getCurrentInstance();
2         ExtendedRenderKitService erks =
3             (ExtendedRenderKitService) Service.getRenderKitService(fc, ExtendedRenderKitService.class);
4 
5         erks.addScript(fc, "window.close();");
复制代码

 

 

62.设置日期为当前日期

如果eo中对应的属性类型为oracle.jbo.domain.Date有以下两种设置 
为当前日期方式

 

        row.setAttribute("Applydate", new oracle.jbo.domain.Date(oracle.jbo.domain.Date.getCurrentDate()));

        oracle.jbo.domain.Date now = new oracle.jbo.domain.Date(new Timestamp(System.currentTimeMillis()));


63.对数据库的操作要谨慎一些有提交就会有回滚善用异常

Example 4–15 Updating an Existing Entity Row

复制代码
 1     /* Update the status of an existing order */
 2     public void updateOrderStatus(long orderId, String newStatus) {
 3         //1. Find the order OrderEOImpl order = retrieveOrderById(orderId);
 4         if (order != null) {
 5             //2. Set its Status attribute to a new value
 6             order.setOrderStatusCode(newStatus);
 7             //3. Commit the transaction
 8             try {
 9                 getDBTransaction().commit();
10             } catch (JboException ex) {
11                 getDBTransaction().rollback();
12                 throw ex;
13             }
14         }
15     }
复制代码

The example for removing an entity row would be the same, except that after finding the existing entity, you would use the following line instead to remove 

the entity before committing the transaction: 
// Remove the entity instead! 
order.remove(); 

64.官方查询标准步骤: 
1.Request begings and application module is acquired 
2.setWhereClause(null) 清除查询提交 
3.setWhereClauseParam(null) 清除查询绑定变量 
4.setWhereWhereClause(...) 
5.setWhereClauseParam(...) 
6.executeQuery() 
7.Application module is released


65.建立View Criteria 查询条件查询

复制代码
 1 import oracle.jbo.ApplicationModule;
 2 import oracle.jbo.Row;
 3 import oracle.jbo.ViewCriteria;
 4 import oracle.jbo.ViewCriteriaRow;
 5 import oracle.jbo.ViewObject;
 6 import oracle.jbo.client.Configuration;
 7 
 8 public class TestClientViewCriteria {
 9     public static void main(String[] args) {
10         String amDef = "devguide.examples.readonlyvo.PersonService";
11         String config = "PersonServiceLocal";
12         ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
13         // 1. Find the view object to filter
14         ViewObject vo = am.findViewObject("PersonList");
15         // Work with your appmodule and view object here
16         Configuration.releaseRootApplicationModule(am, true);
17         // 2. Create a view criteria row set for this view object
18         ViewCriteria vc = vo.createViewCriteria();
19         // 3. Use the view criteria to create one or more view criteria rows
20         ViewCriteriaRow vcr1 = vc.createViewCriteriaRow();
21         ViewCriteriaRow vcr2 = vc.createViewCriteriaRow();
22         // 4. Set attribute values to filter on in appropriate view criteria rows
23         vcr1.setAttribute("PersonId", "> 200");
24         vcr1.setAttribute("Email", "d%");
25         vcr1.setAttribute("PersonTypeCode", "STAFF");
26         // Note the IN operator must be followed by a space after the operator.
27         vcr2.setAttribute("PersonId", "IN (204,206)");
28         vcr2.setAttribute("LastName", "Hemant"); // 5. Add the view criteria rows to the view critera row set
29         vc.add(vcr1);
30         vc.add(vcr2);
31         // 6. Apply the view criteria to the view object
32         vo.applyViewCriteria(vc);
33         // 7. Execute the query
34         vo.executeQuery();
35         while (vo.hasNext()) {
36             Row curPerson = vo.next();
37             System.out.println(curPerson.getAttribute("PersonId") + "" + curPerson.getAttribute("Email"));
38         }
39     }
40 }
复制代码

 


66.使用VO创建新行

复制代码
 1 import oracle.jbo.ApplicationModule;
 2 import oracle.jbo.Row;
 3 import oracle.jbo.ViewObject;
 4 import oracle.jbo.client.Configuration;
 5 import oracle.jbo.domain.DBSequence;
 6 import oracle.jbo.domain.Date;
 7 import oracle.jbo.domain.Timestamp;
 8 
 9 public class TestCreateOrder {
10     public static void main(String[] args) throws Throwable {
11         String amDef = "oracle.fodemo.storefront.store.service.StoreServiceAM";
12         String config = "StoreServiceAMLocal";
13         ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
14         // 1. Find the Orders view object instance.
15         ViewObject orders = am.findViewObject("Orders");
16         // 2. Create a new row and insert it into the row set
17         Row newOrder = orders.createRow();
18         orders.insertRow(newOrder);
19         // Show the entity object-related defaulting for CreatedBy
20         System.out.println("CreatedBy defaults to: " + newOrder.getAttribute("CreatedBy"));
21         // 3. Set values for some of the required attributes
22         Date now = new Date(new Timestamp(System.currentTimeMillis()));
23         newOrder.setAttribute("OrderDate", now);
24         newOrder.setAttribute("OrderStatusCode", "PENDING");
25         newOrder.setAttribute("OrderTotal", 500);
26         newOrder.setAttribute("CustomerId", 110);
27         newOrder.setAttribute("ShipToAddressId", 2);
28         newOrder.setAttribute("ShippingOptionId", 2);
29         newOrder.setAttribute("FreeShippingFlag", "N");
30         newOrder.setAttribute("GiftwrapFlag", "N");
31         // 4. Commit the transaction
32         am.getTransaction().commit();
33         // 5. Retrieve and display the trigger-assigned order id
34         DBSequence id = (DBSequence) newOrder.getAttribute("OrderId");
35         System.out.println("Thanks, reference number is " + id.getSequenceNumber());
36         Configuration.releaseRootApplicationModule(am, true);
37     }
38 }
复制代码

 

67.得到sequence

复制代码
 1     public oracle.jbo.domain.Number getSequenceNumber() {
 2         try {
 3             String seq = "your_db_sequence_name";
 4             oracle.jbo.server.SequenceImpl theSeq = new oracle.jbo.server.SequenceImpl(seq, getDBTransaction());
 5             oracle.jbo.domain.Number seqNextNumber = theSeq.getSequenceNumber();
 6             return seqNextNumber;
 7         } catch (Exception e) {
 8             //handle exceptions
 9         }
10         return null;
11     }
复制代码

绑定方法到页面上之后在bean中调用

复制代码
1     public oracle.jbo.domain.Number getNextEmployeeSequenceNumber() {
2         BindingContext bindingContext = BindingContext.getCurrent();
3         BindingContainer bindings = bindingContext.getCurrentBindingsEntry();
4         OperationBinding getNextSequence = bindings.getOperationBinding("getSequenceNumber");
5         oracle.jbo.domain.Number seqVal = (oracle.jbo.domain.Number) getNextSequence.execute();
6         return seqVal;
7     }
复制代码

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值