basedao.java

来自「一个很好的开源项目管理系统源代码」· Java 代码 · 共 332 行

JAVA
332
字号
package net.java.workeffort.service.dao;import java.beans.PropertyDescriptor;import java.util.Calendar;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Map;import net.java.workeffort.infrastructure.Constants;import net.java.workeffort.infrastructure.context.RequestContextHolder;import net.java.workeffort.infrastructure.exception.IPropertyException;import net.java.workeffort.service.domain.CollectionElement;import net.java.workeffort.service.domain.PageResult;import net.java.workeffort.service.domain.PaginationQuery;import net.java.workeffort.service.support.OptimisticLockingException;import org.apache.commons.beanutils.PropertyUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;/** * This dao implements data access code for iBATIS with transaction management * handled by Spring. * <p> * The SQL exceptions to custom exception translations are done by Spring using * the configurations in <code>sql-error-codes.xml</code> * <p> * Call init() before using this object. * @author Antony Joseph */public class BaseDao extends SqlMapClientDaoSupport implements IBaseDao {    /** the logger */    protected static final Log log = LogFactory.getLog(BaseDao.class);    /** the target database. Used by sql maps for namespace */    protected String database;    public void insert(String statementName, Object obj) {        insert(statementName, obj, true, false);    }    public void insert(String statementName, Object obj, boolean createdDetails) {        insert(statementName, obj, createdDetails, false);    }    public void insert(String statementName, Object obj,            boolean createdDetails, boolean modificationDetails) {        if (getPropertyDescriptor(obj, "version") != null                && getSimpleProperty(obj, "version") == null) {            setSimpleProperty(obj, "version", new Integer(1));        }        if (createdDetails)            populateCreatedDetails(obj);        if (modificationDetails)            populateModificationDetails(obj);        if (logger.isInfoEnabled())            logger.info("Statement:" + statementName + " parameters :" + obj);        getSqlMapClientTemplate().insert(statementName, obj);    }    public void update(String statementName, Object domain)            throws OptimisticLockingException {        update(statementName, domain, true);    }    public void update(String statementName, Object obj,            boolean modificationDetails) throws OptimisticLockingException {        if (modificationDetails)            populateModificationDetails(obj);        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj);        int count = getSqlMapClientTemplate().update(statementName, obj);        if (count < 1)            throw new OptimisticLockingException(statementName);        // Now that the update is complete set version to reflect        // new version in database .        if (getPropertyDescriptor(obj, "version") != null                && getSimpleProperty(obj, "version") != null) {            setSimpleProperty(obj, "version",                    new Integer(((Integer) getSimpleProperty(obj, "version"))                            .intValue() + 1));        }    }    public void delete(String statementName, Object obj)            throws OptimisticLockingException {        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj);        int count = getSqlMapClientTemplate().delete(statementName, obj);        if (count < 1)            throw new OptimisticLockingException(statementName);    }    public Object queryForObject(String statementName, Object obj) {        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj);        return getSqlMapClientTemplate().queryForObject(statementName, obj);    }    public List queryForList(String statementName, Object obj) {        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj);        return getSqlMapClientTemplate().queryForList(statementName, obj);    }    public List queryForList(String statementName, Object obj, int skipResults,            int maxResults) {        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj                    + " skipResults=" + skipResults + " maxResults="                    + maxResults);        return getSqlMapClientTemplate().queryForList(statementName, obj,                skipResults, maxResults);    }    public Map queryForMap(String statementName, Object obj, String keyProperty) {        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj                    + " keyProperty=" + keyProperty);        return getSqlMapClientTemplate().queryForMap(statementName, obj,                keyProperty);    }    public Map queryForMap(String statementName, Object obj,            String keyProperty, String valueProperty) {        if (logger.isInfoEnabled())            logger.info("statement:" + statementName + " parameters:" + obj                    + " keyProperty=" + keyProperty + " valueProperty="                    + valueProperty);        return getSqlMapClientTemplate().queryForMap(statementName, obj,                keyProperty, valueProperty);    }    /**     * Gets the results for a page. The 'rowCount' is the count of total number     * of records that met the search criteria. The records returned will depend     * on properties 'pageIndex' and 'pageSize'.     * <p>     * Note: There should be a related statement name in the sqlmap file :     * statmentName+"Count" to get the count of the total result set.     * <p>     * To keep the network traffic down for hsqldb and mysql the LIMIT clause is     * used. For oracle (Which has nothing similar to the LIMIT clause) we use     * 'in-line views'     * @param statementName The statement name     * @param obj The query object     * @return The page result object (PageResult)     */    public PageResult getPageResult(String statementName, Object obj) {        PageResult result = new PageResult();        List list = queryForList(statementName, obj);        if (((PaginationQuery) obj).getRowCount() == null)            result.setRowCount((Integer) queryForObject(                    statementName + "Count", obj));        else            result.setRowCount(((PaginationQuery) obj).getRowCount());        result.setRows(list);        return result;    }    /**     * Processes multi row inserts, updates, deletes The property "processType"     * (of each row) determines whether the row gets inserted, updated or     * deleted. Note that row "processType" property is set to null if the     * processing succeeds. The 'version' of updated rows get incremented by 1     * to reflect the new 'version' value in the database (version is used for     * optimistic locking).     * @param obj The object     * @param propertyName The property name which contains list of rows     * @param rowCallback The call back object which implements the actual     *            processing     */    public void processRows(Object obj, String propertyName,            IRowCallback rowCallback) {        List list = (List) getSimpleProperty(obj, propertyName);        if (list != null) {            int i = 0;            Iterator it = list.iterator();            while (it.hasNext()) {                Object row = it.next();                try {                    String processType = ((CollectionElement) row)                            .getProcessType();                    if (logger.isInfoEnabled())                        logger.info("processType=" + processType + " row="                                + row);                    if (Constants.PROCESS_TYPE_INSERT.equals(processType)) {                        rowCallback.add(obj, row);                    }                    else if (Constants.PROCESS_TYPE_UPDATE.equals(processType)) {                        rowCallback.modify(obj, row);                    }                    else if (Constants.PROCESS_TYPE_DELETE.equals(processType)) {                        rowCallback.remove(obj, row);                    }                    else if (processType != null && processType.length() > 0) {                        throw new RuntimeException("Invalid processType="                                + processType);                    }                }                catch (ClassCastException cce) {                    throw new RuntimeException(                            "The entry in collection '"                                    + propertyName                                    + "' is not of type 'CollectionElement'. The elements type is "                                    + row.getClass(), cce);                }                catch (RuntimeException e) {                    if (e instanceof IPropertyException) {                        // these are thrown by the callbacks. Set index and                        // collection property name so that the caller can                        // identify which property caused the exception                        ((IPropertyException) e).setIndex(new Integer(i));                        ((IPropertyException) e)                                .setCollectionName(propertyName);                    }                    throw e;                }                i++;            }            // If code reaches here there were no exceptions.            // Get rid of the deleted rows and Reset the processType property            // for all rows            Iterator it2 = list.iterator();            while (it2.hasNext()) {                Object row = it2.next();                String processType = ((CollectionElement) row).getProcessType();                if (Constants.PROCESS_TYPE_DELETE.equals(processType)) {                    it2.remove();                }                else {                    // set the process type to null.                    ((CollectionElement) row).setProcessType(null);                }            }        }        else {            throw new RuntimeException(                    "processRows(). No value for propertyName " + propertyName);        }    }    /**     * @return Returns the database.     */    public String getDatabase() {        return database;    }    /**     * @param database The database to set. Spring IOC     */    public void setDatabase(String database) {        this.database = database;    }    /**     * Returns a date object which is the midnight of the input date.     * @param date The input date     * @return date The midnight date.     */    protected Date getDateMidnight(Date date) {        Calendar cal = Calendar.getInstance();        cal.setTime(date);        cal.set(Calendar.HOUR_OF_DAY, 23);        cal.set(Calendar.MINUTE, 59);        cal.set(Calendar.SECOND, 59);        cal.set(Calendar.MILLISECOND, 0);        return cal.getTime();    }    private void populateCreatedDetails(Object obj) {        setSimpleProperty(obj, "createdBy", RequestContextHolder                .getRequestContext().getSecurityProfile().getPartyCd());        setSimpleProperty(obj, "createdTs", new Date());    }    private void populateModificationDetails(Object obj) {        setSimpleProperty(obj, "lastModifiedBy", RequestContextHolder                .getRequestContext().getSecurityProfile().getPartyCd());        setSimpleProperty(obj, "lastModifiedTs", new Date());    }    private void setSimpleProperty(Object obj, String propertyName, Object value) {        try {            PropertyUtils.setSimpleProperty(obj, propertyName, value);        }        catch (Exception e) {            throw new RuntimeException("Error while setting property:"                    + propertyName + " value:" + value + " on object:" + obj, e);        }    }    private Object getSimpleProperty(Object obj, String propertyName) {        try {            return PropertyUtils.getSimpleProperty(obj, propertyName);        }        catch (Exception e) {            throw new RuntimeException("Error while getting property:"                    + propertyName + " from object:" + obj, e);        }    }    private PropertyDescriptor getPropertyDescriptor(Object obj,            String propertyName) {        try {            return PropertyUtils.getPropertyDescriptor(obj, propertyName);        }        catch (Exception e) {            throw new RuntimeException(                    "Error while getting property descriptor:" + propertyName                            + " from object:" + obj, e);        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?