ibatis实现分页查询

类PageQuery interface IPageQuery
package com.coship.sdp.rights.model.page;

import com.coship.dhm.common.config.impl.XMLFactory;
import java.io.Serializable;

public class PageQuery implements IPageQuery, Serializable
{
    private int PAGE_SIZE_DEFAULT;
    private int beginIndex;
    private int endIndex;
    private int allCount;
    private int currentPage;
    private int pageRowSize;
    private int allPageCount;

    public PageQuery()
    {
        String defaultPageSize = XMLFactory.getValueString("paginatedComponent.defaultPageSize");
        try
        {
            PAGE_SIZE_DEFAULT = Integer.valueOf(defaultPageSize).intValue();
        }
        catch(NumberFormatException e)
        {
            PAGE_SIZE_DEFAULT = 10;
        }
        beginIndex = 1;
        endIndex = 10;
        allCount = 0;
        currentPage = 1;
        pageRowSize = PAGE_SIZE_DEFAULT;
        allPageCount = 0;
    }

    public void calcutePage()
    {
        if(currentPage < 1)
            currentPage = 1;
        if(pageRowSize < 1)
            pageRowSize = PAGE_SIZE_DEFAULT;
        if(allCount % pageRowSize == 0)
            allPageCount = allCount / pageRowSize;
        else
            allPageCount = allCount / pageRowSize + 1;
        if(currentPage >= allPageCount)
            currentPage = allPageCount;
        beginIndex = (currentPage - 1) * pageRowSize > 0 ? (currentPage - 1) * pageRowSize + 1 : 1;
        endIndex = (beginIndex + pageRowSize) - 1;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public int getPageRowSize()
    {
        return pageRowSize;
    }

    public void setPageRowSize(int pageRowSize)
    {
        this.pageRowSize = pageRowSize;
    }

    public int getBeginIndex()
    {
        return beginIndex;
    }

    public void setBeginIndex(int beginIndex)
    {
        this.beginIndex = beginIndex;
    }

    public int getEndIndex()
    {
        return endIndex;
    }

    public void setEndIndex(int endIndex)
    {
        this.endIndex = endIndex;
    }

    public int getAllCount()
    {
        return allCount;
    }

    public void setAllCount(int allCount)
    {
        this.allCount = allCount;
    }

    public int getAllPageCount()
    {
        return allPageCount;
    }

    public void setAllPageCount(int allPageCount)
    {
        this.allPageCount = allPageCount;
    }

}

public interface IPageQuery
{

    public abstract int getBeginIndex();

    public abstract void setBeginIndex(int i);

    public abstract int getEndIndex();

    public abstract void setEndIndex(int i);

    public abstract int getAllCount();

    public abstract void setAllCount(int i);

    public abstract int getCurrentPage();

    public abstract void setCurrentPage(int i);

    public abstract int getPageRowSize();

    public abstract void setPageRowSize(int i);

    public abstract void calcutePage();
}


 /**
     * 查询产品列表
     */
    public IResultPage queryProdOfferingList(Map queryParam, IPageQuery pageQuery) throws DhmException
    {

        log.debug("queryProdOfferingList method start!");

        List resultList = new ArrayList();
        QueryPageDTO queryDTO = new QueryPageDTO();
        BeanUtil.copyProperties(queryDTO, pageQuery);

        List prodOfferingList = null;
        IResultPage resultPage = new ResultPage();

        try
        {
            prodOfferingList = prodOfferingDao.queryProdOfferingList(queryParam, queryDTO);

            if (prodOfferingList != null && prodOfferingList.size() > 0)
            {
                for (ProdOfferingInfo pprodOfferingInfo : prodOfferingList)
                {
                    ProductOffering productOffering = ProdOfferingCovert
                            .copyProertiesForProdOffering(pprodOfferingInfo);
                    resultList.add(productOffering);
                }
            }
            pageQuery.setAllCount(queryDTO.getAllCount());

            resultPage.setResultRows(queryDTO.getAllCount());
            resultPage.setResultList(resultList);

        }
        catch (DataAccessException e)
        {
            throw new DhmException(ErrorCode.COMMON_DB_EXCEPTION, e);
        }
        catch (Exception ex)
        {
            log.error("queryProdOfferingList method error", ex);
            throw new DhmException(ErrorCode.PRODOFFERING_QUERY_ERROR, ex);
        }
        log.debug("queryProdOfferingList method end!");

        return resultPage;
    }
    
    QueryPageDTO、com.ibatis.sqlmap.IQueryPage
    
    
package com.xxx.sdp.rights.dao.page;

import com.ibatis.sqlmap.IQueryPage;
import java.io.Serializable;

public class QueryPageDTO  implements IQueryPage, Serializable
{
    private static final long serialVersionUID = 8347220722610858942L;
    int beginIndex;
    int endIndex;
    int allCount;

    public QueryPageDTO()
    {
        beginIndex = 1;
        endIndex = 10;
        allCount = 0;
    }

    public int getBeginIndex()
    {
        return beginIndex;
    }

    public void setBeginIndex(int beginIndex)
    {
        this.beginIndex = beginIndex;
    }

    public int getEndIndex()
    {
        return endIndex;
    }

    public void setEndIndex(int endIndex)
    {
        this.endIndex = endIndex;
    }

    public int getAllCount()
    {
        return allCount;
    }

    public void setAllCount(int allCount)
    {
        this.allCount = allCount;
    }

}

BeanUtil.copyProperties(queryDTO, pageQuery);
package com.coship.bss.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;

public class BeanUtil
{

    /**
     * 原对象中属性的值不为空则拷贝,否则不拷贝
     *
     * @param dest 需要赋值的对象
     * @param orig 被拷贝的对象
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static void copyProperties(Object dest, Object orig)
    {

        // Validate existence of the specified beans
        if (dest == null)
        {
            return;
        }
        if (orig == null)
        {
            return;
        }

        // Copy the properties, converting as necessary
        if (orig instanceof DynaBean)
        {
            // 从DynaBean中获取属性值
            getFromDynaBean(dest, orig);

        }
        else if (orig instanceof Map)
        {
            // 从Map中获取属性值
            getFromMap(dest, orig);

        }
        else
        /* if (orig is a standard JavaBean) */{
            // 从标准JavaBean获取属性值
            getFromJavaBean(dest, orig);

        }

    }

    /**
     * 从DynaBean中获取属性值
     *
     * */
    private static void getFromDynaBean(Object dest, Object orig)
    {
        DynaProperty origDescriptors[] = ((DynaBean) orig).getDynaClass().getDynaProperties();
        for (int i = 0; i < origDescriptors.length; i++)
        {
            String name = origDescriptors[i].getName();
            if (BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(dest, name))
            {
                Object value = ((DynaBean) orig).get(name);
                if (value != null)
                    try
                    {
                        BeanUtils.copyProperty(dest, name, value);
                    }
                    catch (IllegalAccessException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch (InvocationTargetException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
        }
    }

    /**
     * 从Map中获取属性值
     *
     * */
    private static void getFromMap(Object dest, Object orig)
    {
        Iterator names = ((Map) orig).keySet().iterator();
        while (names.hasNext())
        {
            String name = (String) names.next();
            if (BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(dest, name))
            {
                Object value = ((Map) orig).get(name);
                if (value != null)
                    try
                    {
                        BeanUtils.copyProperty(dest, name, value);
                    }
                    catch (IllegalAccessException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch (InvocationTargetException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
        }
    }

    /**
     * 从标准JavaBean获取属性值
     *
     * */
    private static void getFromJavaBean(Object dest, Object orig)
    {
        PropertyDescriptor origDescriptors[] = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(
                orig);
        for (int i = 0; i < origDescriptors.length; i++)
        {
            String name = origDescriptors[i].getName();
            if ("class".equals(name))
            {
                continue; // No point in trying to set an object's class
            }
            if (BeanUtilsBean.getInstance().getPropertyUtils().isReadable(orig, name)
                    && BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(dest, name))
            {
                try
                {
                    Object value = BeanUtilsBean.getInstance().getPropertyUtils().getSimpleProperty(orig, name);
                    Object destValue = BeanUtilsBean.getInstance().getPropertyUtils().getSimpleProperty(dest, name);
                    if (value != null)
                    {
                        Class origType = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyType(orig, name);
                        Class destType = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyType(dest, name);
                        if (destType != null && !destType.equals(origType) && !checkIsPackageBasicDataType(origType)
                                && !checkIsPackageBasicDataType(destType))
                        {// 非基本数据类型的不同类
                            if (destValue == null)
                            {
                                destValue = destType.newInstance();
                            }
                            BeanUtil.copyProperties(destValue, value);
                            BeanUtilsBean.getInstance().getPropertyUtils().setProperty(dest, name, destValue);
                        }
                        else
                        {
                            BeanUtils.copyProperty(dest, name, value);
                        }
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace(); // Should not happen
                }
            }
        }
    }

    /**
     * 判断Class对象是否为基本数据类型封装类
     *
     * */
    public static boolean checkIsPackageBasicDataType(Class clazz)
    {
        if (String.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz)
                || Boolean.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)
                || clazz.isPrimitive())
        {
            return true;
        }
        return false;
    }
}

public class ProductOfferingDaoImpl extends CoshipSqlMapClientDaoSupport implements IProductOfferingDao
   /**
     * 分页查询产品 返回产品list
     */
    public List queryProdOfferingList(Map paramMap, QueryPageDTO queryPage)
    {
        List result = queryForList("queryProdOfferings", paramMap, queryPage);
        Integer count = (Integer) this.getSqlMapClientTemplate().queryForObject("queryProdOfferingsCount", paramMap);
        queryPage.setAllCount(count);
        return result;
    }
    
    
CoshipSqlMapClientDaoSupport

package com.coship.sdp.rights.dao;

import com.coship.sdp.rights.common.utils.ReflectUtil;
import com.coship.sdp.rights.dao.page.QueryPageDTO;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import java.sql.SQLException;
import java.util.List;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class CoshipSqlMapClientDaoSupport extends SqlMapClientDaoSupport
{

    public CoshipSqlMapClientDaoSupport()
    {
    }

    public void initialize()
        throws Exception
    {
        if(sqlExecutor != null)
        {
            SqlMapClientImpl client = (SqlMapClientImpl)getSqlMapClient();
            com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate delgate = client.getDelegate();
            ReflectUtil.setFieldValue(delgate, "sqlExecutor", com.ibatis.sqlmap.engine.execution.SqlExecutor, sqlExecutor);
        }
    }

    public List queryForList(String statementName, Object obj, QueryPageDTO page)
    {
        return queryForList(statementName, obj, page, true);
    }

    public List queryForList(String statementName, Object obj)
    {
        return getSqlMapClientTemplate().getSqlMapClient().queryForList(statementName, obj);
        SQLException e;
        e;
        throw new DataAccessException(e);
    }

    public List queryForList(String statementName, Object obj, QueryPageDTO page, boolean queryAllCount)
    {
        List result;
        if(queryAllCount)
            page.setAllCount(0);
        int skipResults = page.getBeginIndex();
        int maxResults = (page.getEndIndex() - skipResults) + 1;
        result = getSqlMapClientTemplate().getSqlMapClient().queryForList(statementName, obj, skipResults, maxResults);
        return result;
        SQLException e;
        e;
        throw new DataAccessException(e);
    }

    public SqlExecutor getSqlExecutor()
    {
        return sqlExecutor;
    }

    public void setSqlExecutor(SqlExecutor sqlExecutor)
    {
        this.sqlExecutor = sqlExecutor;
    }

    protected SqlExecutor sqlExecutor;
}

ReflectUtil

package com.coship.sdp.rights.common.utils;

import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;

// Referenced classes of package com.coship.sdp.rights.common.utils:
//            Log

public class ReflectUtil
{
    private static Log logger = Log.getLog(com.coship.sdp.rights.common.utils.ReflectUtil);
    
    public ReflectUtil()
    {
    }

    public static void setFieldValue(Object target, String fname, Class ftype, Object fvalue)
    {
        if(target == null || fname == null || "".equals(fname) || fvalue != null && !ftype.isAssignableFrom(fvalue.getClass()))
            return;
        Class clazz = target.getClass();
        try
        {
            Field field = clazz.getDeclaredField(fname);
            if(!Modifier.isPublic(field.getModifiers()))
                field.setAccessible(true);
            field.set(target, fvalue);
        }
        catch(Exception me)
        {
            if(logger.isDebugEnabled())
                logger.debug(me);
        }
    }

    public static Object copyObject(Object obj)
        throws Exception
    {
        Field fields[] = obj.getClass().getDeclaredFields();
        Object newObj = obj.getClass().newInstance();
        int i = 0;
        for(int j = fields.length; i < j; i++)
        {
            String propertyName = fields[i].getName();
            Object propertyValue = getProperty(obj, propertyName);
            setProperty(newObj, propertyName, propertyValue);
        }

        return newObj;
    }

    private static Object setProperty(Object bean, String propertyName, Object value)
        throws Exception
    {
        Class clazz = bean.getClass();
        Method method;
        Field field = clazz.getDeclaredField(propertyName);
        method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[] {
            field.getType()
        });
        return method.invoke(bean, new Object[] {
            value
        });
        Exception e;
        e;
        throw e;
    }

    private static Object getProperty(Object bean, String propertyName)
        throws Exception
    {
        Class clazz = bean.getClass();
        Method method;
        Field field = clazz.getDeclaredField(propertyName);
        method = clazz.getDeclaredMethod(getGetterName(field.getName()), new Class[0]);
        return method.invoke(bean, new Object[0]);
        Exception e;
        e;
        throw e;
    }

    private static String getGetterName(String propertyName)
    {
        String method = (new StringBuilder()).append("get").append(propertyName.substring(0, 1).toUpperCase()).append(propertyName.substring(1)).toString();
        return method;
    }

    private static String getSetterName(String propertyName)
    {
        String method = (new StringBuilder()).append("set").append(propertyName.substring(0, 1).toUpperCase()).append(propertyName.substring(1)).toString();
        return method;
    }

    public static Map getObjectAsMap(Object obj)
    {
        Map map = new HashMap();
        if(obj == null)
            return map;
        Class clazz = obj.getClass();
        Method methods[] = clazz.getMethods();
        String methodname = "";
        for(int i = 0; i < methods.length; i++)
        {
            methodname = methods[i].getName();
            if(!methodname.startsWith("get"))
                continue;
            try
            {
                Object value = methods[i].invoke(obj, new Object[0]);
                if(value != null && (value instanceof String))
                {
                    String str = (String)value;
                    value = str.trim();
                }
                map.put(getFieldName(methodname), value);
            }
            catch(IllegalArgumentException e)
            {
                logger.debug("Convert JavaBean to Map Error!", e);
            }
            catch(IllegalAccessException e)
            {
                logger.debug("Convert JavaBean to Map Error!", e);
            }
            catch(InvocationTargetException e)
            {
                logger.debug("Convert JavaBean to Map Error!", e);
            }
        }

        return map;
    }

    private static String getFieldName(String str)
    {
        String firstChar = str.substring(3, 4);
        String out = (new StringBuilder()).append(firstChar.toLowerCase()).append(str.substring(4)).toString();
        return out;
    }
}

Log

package com.coship.sdp.rights.common.utils;

import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log
{

    private Log(Class clazz)
    {
        logger = null;
        logger = Logger.getLogger(clazz);
    }

    public static Log getLog(Class clazz)
    {
        return new Log(clazz);
    }

    public boolean isErrorEnabled()
    {
        return logger.isEnabledFor(Level.ERROR);
    }

    public boolean isWarnEnabled()
    {
        return logger.isEnabledFor(Level.WARN);
    }

    public boolean isInfoEnabled()
    {
        return logger.isInfoEnabled();
    }

    public boolean isDebugEnabled()
    {
        return logger.isDebugEnabled();
    }

    public void debug(Object message)
    {
        logger.log(FQCN, Level.DEBUG, getMessage(message), null);
    }

    public void debug(Object message, Throwable th)
    {
        logger.log(FQCN, Level.DEBUG, getMessage(message), th);
    }

    public void info(Object message)
    {
        logger.log(FQCN, Level.INFO, getMessage(message), null);
    }

    public void info(Object message, Throwable th)
    {
        logger.log(FQCN, Level.INFO, getMessage(message), th);
    }

    public void warn(Object message)
    {
        logger.log(FQCN, Level.WARN, getMessage(message), null);
    }

    public void warn(Object message, Throwable th)
    {
        logger.log(FQCN, Level.WARN, getMessage(message), th);
    }

    public void error(Object message)
    {
        logger.log(FQCN, Level.ERROR, getMessage(message), null);
    }

    public void error(Throwable th)
    {
        logger.log(FQCN, Level.ERROR, null, th);
    }

    public void error(Object message, Throwable th)
    {
        logger.log(FQCN, Level.ERROR, getMessage(message), th);
    }

    public void fatal(Object message)
    {
        logger.log(FQCN, Level.FATAL, getMessage(message), null);
    }

    public void fatal(Object message, Throwable th)
    {
        logger.log(FQCN, Level.FATAL, getMessage(message), th);
    }

    private String getMessage(Object obj)
    {
        if(obj == null)
            return "null";
        if(obj instanceof String)
            return (String)obj;
        if(obj instanceof Collection)
        {
            Collection col = (Collection)obj;
            if(!col.isEmpty())
            {
                StringBuilder sb = new StringBuilder();
                Object elem;
                for(Iterator i$ = col.iterator(); i$.hasNext(); sb.append(ReflectionToStringBuilder.toString(elem, ToStringStyle.MULTI_LINE_STYLE)))
                    elem = i$.next();

                return sb.toString();
            } else
            {
                return "Collection is Empty";
            }
        } else
        {
            return ReflectionToStringBuilder.toString(obj, ToStringStyle.MULTI_LINE_STYLE);
        }
    }

    private static final String FQCN = com/coship/sdp/rights/common/utils/Log.getName();
    private Logger logger;

}




 
 
   
 
            
            
 

 
 
 
  
   
  
 
       
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
       
       
       
       
       
       
       
       
       
                      
        
        

 



 
              <%@ include file="/common/pagelist1.jsp" %>


<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>


    
        
            
            
            
            
            
            
            
            
        
    

                
                
                /
                
                  
            

                    
            

                                     class="selectbox_pagenum"
                    οnchange="pageRowSizeChange('pageRowSize1')"
                    list="@com.coship.dhm.common.config.impl.XMLFactory@getValueList(@com.coship.sdp.rights.common.Constants@PAGE_SIZE)">
                

            

                    
            

                                     test="pageQuery.allPageCount eq 0 or pageQuery.currentPage eq 1">
                    <<
                
                
                    <<
                

                
                    <
                

                
                    <
                

                
                
                    >
                

                
                    >
                

                
                    >>
                

                
                    >>
                

            

                    
            

                                     id="pageNo1" οnkeyup="setPageNo(this)" οnblur="setPageNo(this)" />
            

                                     οnclick="goAction('page1')" />
            



      function pageRowSizeChange(id) {
        document.getElementById("pageRowSize").value = document.getElementById(id).value;
        document.getElementById("currentPage").value = 1;
        $("#allCount").attr("value","0");
        var queryFlag = document.getElementById("queryFlag");
        queryFlag.value = 1;
        document.forms["queryForm"].submit();
        setTimeout(function(){load()},3000);
    }


function goAction(op) {
        
        var currentPageEle = document.getElementById("currentPage");
        var currentPage = parseInt(currentPageEle.value);
        var allPageCount = parseInt(document.getElementById("allPageCount").value);
        
        if(op=='page1'){
           var pageNo = document.getElementById("pageNo1").value;
           if(pageNo == null || pageNo <= 0 || pageNo > allPageCount) {
              var confirmDailog = jQuery.extend(Dailog,{
                onOK:function(){            
                }            
              });
              confirmDailog.openWindow('',300,135,'',0,2,0);
              return;
           }
           currentPageEle.value = pageNo;
        } else if(op=='page2'){
           var pageNo = document.getElementById("pageNo2").value;
           if(pageNo == null || pageNo <= 0 || pageNo > allPageCount) {
              var confirmDailog = jQuery.extend(Dailog,{
                onOK:function(){            
                }            
              });
              confirmDailog.openWindow('',300,135,'',0,2,0);
              return;
           }
           currentPageEle.value = pageNo;
        } else if (op=='first') {
           currentPageEle.value = 1;
        } else if (op=='before') {
           currentPageEle.value = currentPage - 1;
        } else if (op=='next') {
           currentPageEle.value = currentPage + 1;
        } else if (op=='end') {
           currentPageEle.value = allPageCount;
        }
       
        var queryFlag = document.getElementById("queryFlag");
        queryFlag.value = 1;
       
        document.forms["queryForm"].submit();
        setTimeout(function(){load()},3000);
    }

你可能感兴趣的:(java,ibatis)