怪怪,我猜你是想每次选出你想要的排序后的某一段,因为ejb ql现在不支持top/rownum之类,所以如果你想在ejb sql里面用between就必须在设计的时候加一个rownum字段,然后用select object(o) from customers o where customers.rownum between ?1 and ?2。 但是如果你的rownum经常变化,需要动态产生,那就没办法了,ejb sql还不像sql那么强大和灵活,所以用cmp方式实现有众多约束,我觉得像你这种情况,比如做报表,还是用bmp好一些,更加灵活。见笑,希望能有所帮助。

解决方案 »

  1.   

    请教楼上的 哪里有关于ejb sql的指南啊? 一直搞不懂ejb sql的语法
    谢谢
      

  2.   

    这个最好还是用sessionBean查询再返回吧
      

  3.   

    回复人: kenny1979(肯) ( ) 信誉:98  2004-09-28 21:36:00  得分: 0  
     
     
       请教楼上的 哪里有关于ejb sql的指南啊? 一直搞不懂ejb sql的语法
    谢谢
      
     
    Top  
     
     回复人: ipv(宁静致远) ( ) 信誉:98  2004-09-29 09:33:00  得分: 0  
     
     
       这个最好还是用sessionBean查询再返回吧
      
     
    Top  
     
    ====================================================================
    同意楼上两位的!!!!!!!!!
      

  4.   

    Chapter 8. CMP: EJB QL
    Find methods have been a part of the Enterprise JavaBeans specification since EJB 1.0. These methods are defined on the entity bean's home interfaces and are used for locating entity beans. All home interfaces must have a findByPrimaryKey( ) method, which takes the primary key of the entity bean as an argument and returns a remote or local reference to that entity bean. For example, the Cruise EJB defines this find method in its home interface as:public CruiseHomeLocal  extends  javax.ejb.EJBLocalHome {  public Integer create(String name,ShipLocal ship)     throws CreateException;      public CruiseLocal findByPrimaryKey(Integer key)     throws FinderException;}
    In addition to the mandatory findByPrimaryKey( ) method, home interfaces can define as many custom find methods as needed. For example, the Cruise EJB might define a method called findByName( ) for locating a Cruise with a specific name:public CruiseHomeLocal extends javax.ejb.EJBLocalHome {  public Integer create(String name,ShipLocal ship)    throws CreateException;      public CruiseLocal findByPrimaryKey(Integer key)    throws FinderException;  public CruiseLocal findByName(String cruiseName)   throws FinderException;}
    It's not obvious to the container how a custom find method should behave. In EJB 1.0 and 1.1, vendors came up with their own query languages and methods to specify the behavior of these other solutions. Consequently, the custom methods generally were not portable, and guesswork was required on the part of the deployer to determine how to properly execute queries against them. EJB 2.0 introduced the Enterprise JavaBeans Query Language (EJB QL)—a standard query language for declaring the behavior of custom find methods—and the new select methods. Select methods are similar to find methods, but they are more flexible and are visible to the bean class only. Find and select methods are collectively referred to as query methods. EJB 2.1 enhances EJB QL by adding aggregate functions, the ORDER BY clause, and other new features. The differences in EJB QL between EJB 2.1 and EJB 2.0 are clearly stated throughout this chapter.EJB QL is a declarative query language similar to the Structured Query Language (SQL) used in relational databases, but it is tailored to work with the abstract persistence schema of entity beans. EJB QL queries are defined in terms of the abstract persistence schema of entity beans and not the underlying data store, so they are portable across databases and data schemas. When an entity bean's abstract bean class is deployed, the EJB QL statements are translated into data access code optimized for a specific data store. At runtime, query methods defined in EJB QL usually execute in the native language of the underlying data store. For example, a container that uses a relational database for persistence might translate EJB QL statements into standard SQL 92, while an object-database container might translate the same EJB QL statements into an object query language.EJB QL makes it possible to define queries that are portable across databases and EJB vendors. The EJB QL language is easy for developers to learn, yet precise enough to be interpreted into native database code. It is a rich and flexible query language that empowers developers, while executing in fast native code at runtime. However, EJB QL is not a silver bullet and is not without its problems, as we'll see later in this chapter.
      

  5.   

    8.1 Declaring EJB QL
    EJB QL statements are declared in <query> elements in an entity bean's deployment descriptor. In the following listing, the findByName( ) method defined in the Cruise bean's local home interface has its own query element and EJB QL statement:<ejb-jar ...>    <enterprise-beans>        <entity>            <ejb-name>CruiseEJB</ejb-name>            ...            <reentrant>False</reentrant>            <abstract-schema-name>Cruise</abstract-schema-name>            <cmp-version>2.x</cmp-version>            <cmp-field>                   <field-name>name</field-name>            </cmp-field>            <primkey-field>id</primkey-field>            <query>             <query-method>               <method-name>findByName</method-name>               <method-params>                 <method-param>java.lang.String</method-param>               </method-params>             </query-method>             <ejb-ql>               SELECT OBJECT(c) FROM Cruise AS c                WHERE c.name = ?1             </ejb-ql>            </query>        </entity>    </enterprise-beans></ejb-jar>
    The <query> element contains two primary elements. The <query-method> element identifies a particular find method, and the <ejb-ql> element declares the EJB QL statement. The <query> element binds the EJB QL statement to the proper find method. Don't worry too much about the EJB QL statement just yet; we'll cover that in detail starting in the next section.Every entity bean that is referenced in an EJB QL statement must have a special designator called an abstract schema name, which is declared by the <abstract-schema-name> element. Each element must declare a unique name. These names must be unique: no two entity beans may have the same abstract schema name. In the entity element that describes the Cruise EJB, the abstract schema name is declared as Cruise. The <ejb-ql> element contains an EJB QL statement that uses this identifier in its FROM clause. 
      

  6.   

    8.2 The Query Methods
    There are two main types of query methods: find methods and select methods. These are discussed in the following sections.8.2.1 Find Methods
    Find methods are invoked by EJB clients (applications or beans) to obtain EJB object references to specific entity beans. For example, you might call the findByPrimaryKey( ) method on the Customer EJB's home interface to obtain a reference to a specific Customer bean.Find methods are always declared in the local and remote home interfaces of an entity bean. Specifying a single remote or local return type for a find method indicates that the method locates only one bean. findByPrimaryKey( ) obviously returns a single remote reference, because there is a one-to-one correspondence between a primary key's value and an entity. Other single-entity find methods can also be declared. For example, in the following code segment the Customer EJB declares several single-entity find methods, each of which supports a different query:public interface CustomerHomeRemote extends javax.ejb.EJBHome {    public CustomerRemote findByPrimaryKey(Integer primaryKey)        throws javax.ejb.FinderException, java.rmi.RemoteException;    public CustomerRemote findByName(String lastName, String firstName)        throws javax.ejb.FinderException, java.rmi.RemoteException;    public CustomerRemote findBySSN(String socialSecurityNumber)        throws javax.ejb.FinderException, java.rmi.RemoteException;}
    Bean developers can also define multi-entity find methods, which return a collection of EJB objects. The following listing shows a couple of multi-entity find methods:public interface CustomerHomeLocal extends javax.ejb.EJBLocalHome {    public CustomerLocal findByPrimaryKey(Integer primaryKey)        throws javax.ejb.FinderException;    public Collection findByCity(String city,String state)        throws javax.ejb.FinderException;    public Collection findByGoodCredit( )        throws javax.ejb.FinderException;}
    To return several references from a find method, you must use a java.util.Collection type.[1] A find method that uses this return type may have duplicates. To avoid duplicates, use the keyword DISTINCT in the EJB QL statement associated with the find method. Multi-entity finds return an empty Collection if no matching beans are found.[1] In The java.util.Collection is the only collection type supported for multi-entity find methods in CMP.All query methods (find or select) must be declared as throwing the javax.ejb.FinderException. Find methods that return a single remote reference throw a FinderException if an application error occurs and a javax.ejb.ObjectNotFoundException if a matching bean cannot be found. The ObjectNotFoundException is a subtype of FinderException that is thrown only by single-entity find methods.With the exception of findByPrimaryKey( ) methods, all find methods must be declared in <query> elements in the bean's deployment descriptor. Query declarations for findByPrimaryKey( ) methods are not necessary and, in fact, are forbidden. It's obvious what this method should do, and you may not try to change its behavior. The following snippet from the Customer EJB's deployment descriptor shows declarations of two find methods, findByName( ) and findByGoodCredit( ):<query>    <query-method>        <method-name>findByName</method-name>        <method-params>            <method-param>java.lang.String</method-param>            <method-param>java.lang.String</method-param>        </method-params>    </query-method>    <ejb-ql>        SELECT OBJECT(c) FROM Customer AS c         WHERE c.lastName = ?1 AND c.firstName = ?2    </ejb-ql></query><query>    <query-method>        <method-name>findByGoodCredit</method-name>        <method-params/>    </query-method>    <ejb-ql>        SELECT OBJECT(c) FROM Customer AS c        WHERE c.hasGoodCredit = TRUE    </ejb-ql></query>
    The <query> elements allow the bean developer to associate EJB QL statements with specific find methods. When the bean is deployed, the container attempts to match the find method declared in each of the query elements with find methods in the entity bean's home interfaces. To do so, it matches the values of the <method-name> and <method-params> elements with method names and parameter types (ordering is important) in the home interfaces.When two find methods have the same method name and parameters, the query declaration applies to both methods. (This situation occurs when similar find methods are in the local home and remote home interfaces.) The container returns the proper type for each query method: the remote home returns remote EJB objects, and the local home returns local EJB objects. You can therefore define the behavior of both the local and remote home find methods using a single <query> element, which is convenient if you want local clients to have access to the same find methods as remote clients.The <ejb-ql> element specifies the EJB QL statement for a specific find method. EJB QL statements can use input parameters (e.g., ?1, ?2, ... ?n), which are mapped to the <method-param> elements of the find method, as well as literals (e.g., TRUE).
      

  7.   

    利用cmp来实现分页显示,需要自己对查询结果进行提取操作,下面是一段实现代码,你可以看看
    public class PageForm implements Serializable{
     private int valueCount=0;  //记录总数
     private int pageSize=10;   //每页面的记录数
     private int pageCount=0;   //页面总数
     private int pagePos=0;     //当前页面
     private boolean hasPre=false;   //是否能向前翻页
     private boolean hasNext=false;  //是否能向后翻页
     private String[] pageList;         //所有的页码数 public PageForm(int count,int size,int pos) {
       this.valueCount=count;
       this.pageSize=size;
       this.pagePos=pos;   //设置页码数目
       this.pageCount=count/size;
       pageCount=pageCount*size<count? (pageCount+1):pageCount;   //设置向前导航的开关
       if(pos*pageSize>=valueCount)hasNext=false;
       else hasNext=true;   //设置向后导航的开关
       if(pos==1)this.hasPre=false;
       else this.hasPre=true;   this.pageList=this.creatPageList();
     }
     /**
      * 生成页码列表
      * @return int[]
      */
     public String[]  creatPageList(){
       String [] pages=new String[this.pageCount];
       for(int i=0;i<this.pageCount;i++){
         int pos=i+1;     pages[i]=""+pos;
       }
       return pages;
     }
     /**
      * 判断是否能够向上翻面
      * @return boolean  如果能够向上翻页,返回true ,否则 返回false
      */
     public boolean isHasNext() {
       return hasNext;
     }
     /**
      * 判断是否能够向下翻面
      * @return boolean 如果能够向上翻页,返回true ,否则 返回false
      */
     public boolean isHasPre() {
       return hasPre;
     }
     public int getPageSize() {
       return pageSize;
     }
     public int getPggeCount() {
       return pageCount;
     }
     public int getValueCount() {
       return valueCount;
     }
     public int getPageCount() {
       return pageCount;
     }
     public int getPagePos() {
       return pagePos;
     }
     public String[] getPageList() {
       return pageList;
      }}
      

  8.   

    有点懂了 谢谢 sobluesky(期盼陆地的鸟)
      

  9.   

    8.2.2 Select Methods
    Select methods are similar to find methods, but they are more versatile and can be used only internally, by the bean class. In other words, select methods are private query methods; they are not exposed to an entity bean's interfaces.Select and find methods also execute in different transaction contexts. The select method executes in the transaction context of the business or callback method that is using it, while the find methods execute according to their own transaction attributes, as specified by the bean provider.Select methods are declared as abstract methods using the naming convention ejbSelect<METHOD-NAME>. Here are four select methods declared in the AddressBean class:public class AddressBean implements javax.ejb.EntityBean {    ...    public abstract String ejbSelectMostPopularCity( )        throws FinderException;        public abstract Set ejbSelectZipCodes(String state)        throws FinderException;    public abstract Collection ejbSelectAll( )        throws FinderException;    public abstract CustomerLocal ejbSelectCustomer(AddressLocal addr)        throws FinderException;    ...}
    Select methods can return the values of CMP fields. The ejbSelectMostPopularCity( ) method, for example, returns a single String value, the name of the city referenced by the most Address EJBs.To return several references from a select method, you must declare the return type to be either a Collection or a Set.[2] Which type to return depends on whether you want to allow duplicate values. By definition, a Set never contains duplicates, while a Collection may have duplicates. Multi-entity selects return an empty Collection or Set if no matching beans are found. For example, the ejbSelectZipCodes( ) method returns a java.util.Set of String values: a unique collection of all the Zip codes declared for the Address EJBs for a specific state.[2] Other collection types, such as java.util.List and java.util.Map, may be added in future versions.Like find methods, select methods can declare arguments that limit the scope of the query. For example, the ejbSelectZipCodes( ) and ejbSelectCustomer( ) methods declare arguments that limit the scope of the results. These arguments are used as input parameters in the EJB QL statements assigned to the select methods.Select methods can return local or remote EJB objects. Whether a single-entity select method returns a local or a remote object is determined by the return type of the ejbSelect( ) method. The ejbSelectCustomer( ) method, for example, returns a local EJB object, the CustomerLocal. This method could easily have been defined to return a remote object by changing the return type to the Customer bean's remote interface (CustomerRemote). Multi-entity select methods, which return a collection of EJB objects, return local EJB objects by default. However, you can override this behavior by using the <result-type-mapping> element in the select method's <query> element.The following snippet from an XML deployment descriptor declares two select methods. Notice that they are exactly the same as the find method declarations:<query>    <query-method>      <method-name>ejbSelectZipCodes</method-name>      <method-params>      <method-param>java.lang.String</method-param>      </method-params>    </query-method>    <ejb-ql>        SELECT a.homeAddress.zip FROM Address AS a        WHERE a.homeAddress.state = ?1    </ejb-ql></query><query>    <query-method>        <method-name>ejbSelectAll</method-name>        <method-params/>        </query-method>    <result-type-mapping>Remote</result-type-mapping>    <ejb-ql>        SELECT OBJECT(a) FROM Address AS a    </ejb-ql></query>
    The name given in each <method-name> element must match one of the ejbSelect<METHOD-NAME>( ) methods defined in the bean class. This is different from find methods in CMP, which use the names of select methods defined by the bean class.By default, the <result-type-mapping> element in the value of <result-type-mapping> can be either Remote or Local. Local indicates that the select method should return local EJB objects; Remote indicates remote EJB objects. For a single-entity select, the actual return type of the ejbSelect( ) method must match the <result-type-mapping>. In the previous example, the <result-type-mapping> element for the ejbSelectAll( ) method is declared as Remote, which means the query should return remote EJB object types (i.e., remote references to the Address EJB).[3][3] This is illustrative. As a developer, it is unlikely (although possible) that you would define a remote interface for the Address EJB, because it is too fine-grained for use by remote clients.Select methods can be used to query all the entity beans declared in the same deployment descriptor. Select methods may be called by a bean's ejbHome( ) methods, by any business methods, or by the ejbLoad( ) and ejbStore( ) methods. In most cases, select methods will be called by ejbHome( ) or by business methods in the bean class.The most important thing to remember about select methods is that while they can do anything find methods can and more, they can be used only by the entity bean class that declares them, not by the entity bean's clients. 
      

  10.   

    8.4 Problems with EJB QL
    EJB QL is a powerful new tool that promises to improve performance, flexibility, and portability of entity beans in container-managed persistence, but it has some design flaws and omissions.8.4.1 The OBJECT( ) Operator
    The use of the OBJECT( ) operator is cumbersome and provides little or no value to the bean developer. It's trivial for EJB vendors to determine when an abstract schema type is the return value, so the OBJECT( ) operator provides little real value during query translation. In addition, the OBJECT( ) operator is applied haphazardly. It's required when the return type is an abstract schema identifier, but not when a path expression of the SELECT clause ends in a CMR field. Both return an EJB object reference, so the use of OBJECT( ) in one scenario and not the other is illogical and confusing.When questioned about this, Sun replied that several vendors had requested the use of the OBJECT( ) operator because it will be included in the next major release of the SQL programming language. EJB QL was designed to be similar to SQL because SQL is the query language that is most familiar to developers, but this doesn't mean it should include functions and operations that have no real meaning in Enterprise JavaBeans.8.4.2 Lack of Support for Date
    EJB QL doesn't provide native support for the java.util.Date class. The java.util.Date class should be supported as a natural type in EJB QL. It should be possible, for example, to do comparisons with Date CMP fields and literal and input parameters using comparison operators (=, >, >=, <, <=, <>). It should also be possible to introduce common date functions so that comparisons can be done at different levels, such as comparing the day of the week (DOW( )) or month (MONTH( )), etc. In addition, date literals should be supported. For example, a literal like "2004-04-02" for April 2nd, 2004 should be acceptable as a literal. Of course, supporting Date types and literals in EJB QL is not trivial and problems with interpretation of dates and locales would need to be considered, but the failure to address Date as a supported type is significant.8.4.3 Limited Functions
    While the aggregate functions and functional expressions provided by EJB QL are valuable to developers, many other functions should also be added. For example, CAST( ) (useful for comparing different types) and date functions, such as DOW( ), MONTH( ), etc., could be added. The UPPER( ) and LOWER( ) functional expressions should also be added—they make it possible to do caseless comparisons in the LIKE clause. EJB 2.1 adds some functions to the SELECT clause, including COUNT( ), SUM( ), AVG( ), MAX( ), and MIN( ).
     
     
    8.4.4 Multiple SELECT Expressions
    In EJB 2.0 and 2.1, EJB QL statements can only declare a single SELECT expression. In other words, it's not possible to SELECT multiple items. The following query is illegal:SELECT addr.city, addr.stateFROM Address AS addr
    Today, you can only select either the city or the state, but not both.8.4.5 GROUP BY and HAVING
    In SQL, the GROUP BY and HAVING clauses are commonly used to apply stricter organization to a query and narrowing the results for aggregate functions. The GROUP BY clause is usually used in combination with aggregate functions, because it allows you to cluster data by category. For example, the following query provides a count for all the cities in each state:SELECT addr.state, COUNT(addr.city)FROM Address AS addrGROUP BY addr.state
    The HAVING clause is used with a GROUP BY clause and acts as a filter, restricting the final output. The HAVING clause employs aggregate functional expressions using only the identifiers used in the SELECT clause. For example, the following query uses the GROUP BY and HAVING clauses to select and count only the states with more than 200 cities:SELECT addr.state, COUNT(addr.city)FROM Address AS addrGROUP BY addr.stateHAVING COUNT(addr.city) > 200
    8.4.6 Subqueries
    Subqueries can be useful; they are common to SQL and some other query languages. A subquery is a SELECT statement inside of another SELECT statement, usually in the WHERE, SELECT, or HAVING clause. For example, the following subquery finds the average amount paid for a reservation, a value that is subsequently used to find all reservations where the amount paid is greater than the average.SELECT  OBJECT(res)FROM Reservations AS resWHERE res.amountPaid >=      ( SELECT AVG(r.amountPaid) FROM Cruise AS c, IN( c.reservations ) AS r          WHERE c = ?1   )
    8.4.7 Dynamic Queries
    Dynamic queries are supported by most vendors, but not the specification. In EJB 2.0 and 2.1, all EJB QL statements are statically compiled at deployment time. In other words, you can't make up a query on the fly and submit it to the EJB container system. This restriction makes it difficult to create reports and do analysis because you always have to know the queries before the beans are deployed. Most vendors already support dynamic queries—it's a mystery why EJB QL doesn't. 
      

  11.   

    我觉得从这个问题可以看出ejb只是一种模式,尤其是bmp,是访问数据库的一种模式。ejb3.0出来,ejb 增强了许多,但是还是无法实现足够的功能,归根结底还是,需要bmp的形式作为补充,所以,cmp不是什么好东西,就像好货部便宜。bmp才更管用。
      

  12.   

    我觉得的数据的显示这种不用修改数据库的操作还是用JDBC来做好.
    such petstore
      

  13.   

    我刚才开了一个贴,没人顶我,借个机会问个问题,包括楼主在内,回答好了我另开帖给分!
    我做了个CMP,编译都通过了,同时(127.0.0.1/console里边已经配置好JNDI=DATASOURCE)
    ,但是我deploy的时候 出现如下错误:Unable to deploy EJB: BmGs from CMP.jar:
    Null keys not supported.
    Nested Exception: java.lang.IllegalArgumentException: Null keys not supported////说我有空键,但是没有啊,我到数据库查了啊
      

  14.   

    to  tangboyong() 
    系统是说你的CMP没有主键,而非你的数据库表有没有主键
      

  15.   

    cmp什么东西,好玩吗?那里有下的,是那家游戏公司开发的?
      

  16.   

    cmp来做分页处理,绝对不是个好方法:)
      

  17.   

    可是cmp要是不分页的话,要是有上万条记录,一次性选出来,效率回很低!
      

  18.   

    这是ouhua(要坚强,不要懦弱) 在
    http://community.csdn.net/Expert/topic/3476/3476580.xml?temp=.258938
    中的发言,我觉得蛮好的:方法一:JDBC+SQL,利用数据库的SQL特性,如Oracle,可以直接从数据库返回你要的数据数量,如10条。
    方法二:CMP Entity Bean,思路是先从数据库查询出一个主键集合(Collection),这是一个大的集合,也有几十万个元素,不过因为集合元素只是主键字段,所以占用内存也不大。然后根据集合中的主键使用findByPrimaryKey()查询出指定数量的记录并建立VO List,这样就可以实现分页。在这种情况下应该利用应用服务器(如WebLogic)的一些特性,如事务结束后更新等功能。这样的话,第一次分页是两次查询数据库,以后的分页就可以一次查询数据库(利用以前的集合),性能肯定不会差。
      

  19.   

    这是ouhua(要坚强,不要懦弱) 在
    http://community.csdn.net/Expert/topic/3476/3476580.xml?temp=.258938
    中的发言,我觉得蛮好的:方法一:JDBC+SQL,利用数据库的SQL特性,如Oracle,可以直接从数据库返回你要的数据数量,如10条。
    方法二:CMP Entity Bean,思路是先从数据库查询出一个主键集合(Collection),这是一个大的集合,也有几十万个元素,不过因为集合元素只是主键字段,所以占用内存也不大。然后根据集合中的主键使用findByPrimaryKey()查询出指定数量的记录并建立VO List,这样就可以实现分页。在这种情况下应该利用应用服务器(如WebLogic)的一些特性,如事务结束后更新等功能。这样的话,第一次分页是两次查询数据库,以后的分页就可以一次查询数据库(利用以前的集合),性能肯定不会差。
      

  20.   

    EJB是什么东西啊?JAVABEAN又是什么呢?是微软的产品吗?怎么好象没听过?导师好象也讲过什么BEAN的,还有什么JAVA的,是不是微软的东西啊?
      

  21.   

    完全只读的数据最好不要在EJB中来实现,这个是对EJB的一个冲撞
    JDBC是个好方法
      

  22.   

    同意。ejb做这些东西的话不是很好。
      

  23.   

    给你一个jdbc做的。
    public class PageBean {
    private int totalPage;
    private int curPage = 1;
    private int nextPage;
    private int perPage = 20;
    private int previousPage;
    private int firstPage;
    private int lastPage;
    private String sql;
    private String orderBy = "";
    private int count;
    public int getTotalPage() {
    return totalPage;
    } public PageBean() {
    } public void setCurPage(int curPage) {
    this.curPage = curPage;
    } public int getCurPage() {
    return curPage;
    } public int getNextPage() {
    if (getCurPage() == this.totalPage) {
    return this.totalPage; //到了最后面
    }
    else {
    return this.getCurPage() + 1;
    }
    } public void setPerPage(int perPage) {
    this.perPage = perPage;
    } public int getPerPage() {
    return perPage;
    } public int getPreviousPage() {
    if (this.getCurPage() == 1) {
    return 1; //到了最前面
    }
    else {
    return this.getCurPage() - 1;
    }
    } public void inital() {
    int i = 0;
    try {
    DB mydb = new DB();
    String query = "select count(*) num from (" + this.sql + ")";
    CachedRowSet rs = mydb.executeQuery(query);
    System.out.println(sql);
    rs.next();
    this.setCount(rs.getInt("num"));
    if (rs.getInt("num") % this.getPerPage() == 0) {
    i = rs.getInt("num") / this.getPerPage();
    }
    else {
    i = rs.getInt("num") / this.getPerPage() + 1;
    }
    System.out.println("total num:" + rs.getInt("num"));
    if (rs.getInt("num") == 0) {
    i = 1;
    }
    this.totalPage = i;
    this.firstPage = 1;
    this.lastPage = i;
    }
    catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    /**
      public CachedRowSet getRecord() {
    CachedRowSet rs = null;
    DB mydb = new DB();
    try {
      int i = curPage - 1;
      String query = null;
      query = "select * from (select * from (" + sql + ") where rownum<=" +
      this.perPage * this.curPage + " minus select * from (" + sql +
      ") where rownum<=" +
      this.perPage * (this.curPage - 1) + ") " + this.orderBy;
      System.out.println(query);
      rs = mydb.executeQuery(query);
    }
    catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return rs;
      }
    */ public CachedRowSet getRecord(String sql, int curpage, int perpage) {
    OpenDbBean db = new OpenDbBean();
    Connection conn = null;
    ResultSet rs = null;
    CachedRowSet crs = null;
    Statement sqlStmt = null;
    try {
    crs = new CachedRowSet();
    conn = db.getConnection();
    sqlStmt =
    conn.createStatement(
    java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
    java.sql.ResultSet.CONCUR_READ_ONLY);
    //执行SQL语句并获取结果集
    ResultSet rs1 = sqlStmt.executeQuery(sql);
    if (rs1.next()) {
    rs = sqlStmt.executeQuery(sql);
    //将记录指针定位到待显示页的第一条记录上
    if (curpage > 1) {
    rs.absolute((curpage - 1) * perpage);
    }
    crs.populate(rs);
    }
    return crs;
    }
    catch (SQLException ex) {
    System.out.println(ex.getMessage());
    return null;
    }
    finally {
    try {
    db.CleanConnection(conn, sqlStmt, rs);
    }
    catch (SQLException ex1) {
    }
    }
    } public CachedRowSet getRecord() {
    OpenDbBean db = new OpenDbBean();
    Connection conn = null;
    ResultSet rs = null;
    CachedRowSet crs = null;
    Statement sqlStmt = null;
    try {
    crs = new CachedRowSet();
    conn = db.getConnection();
    sqlStmt =
    conn.createStatement(
    java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
    java.sql.ResultSet.CONCUR_READ_ONLY);
    //执行SQL语句并获取结果集
    rs = sqlStmt.executeQuery(this.sql);
    if (this.totalPage > 0) {
    //将记录指针定位到待显示页的第一条记录上
    if (this.curPage > 1) {
    rs.absolute((this.curPage - 1) * this.perPage);
    }
    crs.populate(rs);
    }
    return crs;
    }
    catch (SQLException ex) {
    System.out.println(ex.getMessage());
    return null;
    }
    finally {
    try {
    db.CleanConnection(conn, sqlStmt, rs);
    }
    catch (SQLException ex1) {
    }
    }
    } public static void main(String[] args) {
    PageBean mypage = new PageBean();
    mypage.setPerPage(5);
    mypage.setCurPage(0);
    mypage.setSql("select * from a");
    mypage.inital();
    System.out.println("taltal page:" + mypage.getTotalPage());
    System.out.println("nextpage:" + mypage.getNextPage());
    System.out.println("prepage:" + mypage.getPreviousPage());
    CachedRowSet rs = mypage.getRecord();
    try {
    int i = 0;
    ;
    while (rs.next() && i < mypage.getPerPage()) {
    System.out.println(rs.getString(1));
    i++;
    }
    }
    catch (Exception e) {
    System.out.println(e.getMessage());
    }
    } public int getFirstPage() {
    return firstPage;
    } public void setFirstPage(int firstPage) {
    this.firstPage = firstPage;
    } public int getLastPage() {
    return lastPage;
    } public void setLastPage(int lastPage) {
    this.lastPage = lastPage;
    } public String getSql() {
    return sql;
    } public void setSql(String sql) {
    this.sql = sql;
    } public String getOrderBy() {
    return orderBy;
    } public void setOrderBy(String orderBy) {
    this.orderBy = orderBy;
    }
    public int getCount() {
    return count;
    }
    public void setCount(int count) {
    this.count = count;
    }
    }
      

  24.   

    被注释部分也可以用,如果数据量不是很大的话。如果数据量大效率比较低。是用sql来分页的。没有注释的部分是用游标来分的sql效率高。但是费内存。
      

  25.   

    活活,我提供一种做法,不过就是有点慢,而且非内存。
    就是用ejb将数据查出来后放到一个hashMap中去,然后再在hashMap里面对他进行分页。可以实现的。
      

  26.   

    如果使用jdbc 直接读取数据库实现分页,大多数数据库都是可以的,因为是read commited.但如果一次全都load进来,那就会有read uncommited的问题。ejb3.0将会给ejb-ql升级,到时候就会完美地解决这个问题了。