由于最近接手的项目中大量用到EJB1.0的BMP,数据量过大的时候就不得不采取分页显示的解决方法。由于对BMP了解并不太久,下面我采用的方法,由于不得不为每个要分页的BMP加两个方法感觉也是权益之计,不知道是否有更好的方法分页,仅当抛砖引玉吧。
1,在远程Home接口中加下面两个方法:
public interface MyTableHome extends EJBHome
{
//
public Collection findByPage(String strCond,int rownumbegin,int rownumend) throws RemoteException, FinderException;
public int getCount(String strCond) throws RemoteException;
}
2,在BMP中也加相应的方法:
public class MyTableBeanBMP extends MyTableBean
{
//
public Collection ejbFindByPage(String strCond,int rownumbegin,int rownumend)
{
Connection connection = null;
PreparedStatement statement = null;
try
{
connection = dataSource.getConnection();
statement = connection.prepareStatement("SELECT ID from (select t.*, rownum row_num from MYTABLE t "+strCond+") a where a.row_num between "+rownumbegin+" and "+rownumend+"");
ResultSet resultSet = statement.executeQuery();
Vector keys = new Vector();
while (resultSet.next())
{
String cCode = resultSet.getString(1);
keys.addElement(cCode);
}
return keys;
}
catch(SQLException e)
{
throw new EJBException("Error executing SQL SELECT ID from (select t.*, rownum row_num from MYTABLE t "+strCond+") a where a.row_num between "+rownumbegin+" and "+rownumend+" : " + e.toString());
}
finally
{
closeConnection(connection, statement);
}
}
public int ejbHomeGetCount(String strCond)
{
Connection connection = null;
PreparedStatement statement = null;
try
{
connection = dataSource.getConnection();
statement = connection.prepareStatement("SELECT count(*) from MYTABLE "+strCond);
ResultSet resultSet = statement.executeQuery();
int count = 1;
while (resultSet.next())
{
count = resultSet.getInt(1);
}
return count;
}
catch(SQLException e)
{
throw new EJBException("Error executing SELECT count(*) from MYTABLE "+strCond+" : " + e.toString());
}
finally
{
closeConnection(connection, statement);
}
}
}
3.调用:
int maxrowinpage = 15;//每页显示15条记录
int Page = 1;
int rowcount = 0;
int maxpage = 0;
int rownumbegin =1;
int rownumend =maxrowinpage;
String strCond =" "; //查询条件
Context context = new InitialContext();
Object ref = context.lookup("MyTable");
MyTableHome home = (MyTableHome) ref;
rowcount = home.getCount(strCond);
maxpage = (rowcount + maxrowinpage - 1) / maxrowinpage;
rownumbegin = (Page-1)*maxrowinpage+1;
rownumend = Page*maxrowinpage;
Collection c = home.findByPage(strCond,rownumbegin,rownumend);