Package com.wizriver.dao

Source Code of com.wizriver.dao.DefaultBaseManager

package com.wizriver.dao;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import ognl.Ognl;
import ognl.OgnlException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.wizriver.entity.DomainModel;
import com.wizriver.entity.VgEntity;
import com.wizriver.utils.PropertyUtils;

/**   
*    
* @Project_name: jinbawang   
* @Class_name: DefaultBaseManager   
* @Description:
* @Author: <a href="mailto:bobo2581@gmail.com">bobo</a>   
* @Create_date:2012-7-10 下午02:42:27 
* @Modifier:
* @Modification_time:2012-7-10 下午02:42:27  
* @Modify_note:    
* @version:
*    
*/
public class DefaultBaseManager implements BaseManager,ApplicationContextAware {
  protected final Log logger = LogFactory.getLog(this.getClass());
  protected CommonDao commonDao;
  protected ApplicationContext applicationContext;
  protected HibernateTransactionManager transactionManager;
  private SequenceGenerater sequenceGenerater;
  protected SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
 
  public void delete(VgEntity entity) {
    commonDao.delete(entity);
  }
 
  /**
   * 只将vo中不为null的属性赋值给po
   * @param vo
   * @param po
   */
  @SuppressWarnings("unchecked")
  public void copyProperty(VgEntity vo , VgEntity po) throws Exception {
   

    Field[] fields = extractAllFields(vo.getClass());
    for (int i = 0 ; i < fields.length ; i ++) {
      if("version".equals(fields[i].getName())){
        continue;
      }
      Object voValue = getProperty(vo , fields[i].getName());
      Class clazz = PropertyUtils.getPropertyType(vo.getClass(),fields[i].getName());
      if(isAutoCopyEnabled(clazz,voValue)){
        //处理外键
        if(voValue != null && VgEntity.class.isAssignableFrom(voValue.getClass()) && (((VgEntity)voValue).getId() == null || ((VgEntity)voValue).getId() == 0L)){
          voValue  = null;
        }
        if(logger.isDebugEnabled()){
          logger.debug("Property [" + fields[i].getName() + "] with value [" + voValue + "] copyed from VO");
        }
        org.apache.commons.beanutils.PropertyUtils.setProperty(po , fields[i].getName() , voValue);
      }
    }
  }
 
  @SuppressWarnings("unchecked")
  private Field[] extractAllFields(Class clazz) {
    List<Field> result = new ArrayList<Field>();
    while(!clazz.isAssignableFrom(VgEntity.class)){
      result.addAll(Arrays.asList(clazz.getDeclaredFields()));
      clazz = clazz.getSuperclass();
    }
    return (Field[])result.toArray(new Field[0]);
  }

  @SuppressWarnings("unchecked")
  private boolean isAutoCopyEnabled(Class clazz, Object voValue) {
    boolean enabled = false;
    if(voValue == null){
      enabled = false;
    }
    else{ //voValue != null
      if(PropertyUtils.isPrimitiveType(clazz)){
        enabled = true;
      }else if(DomainModel.class.isAssignableFrom(clazz)){//组键类型
        enabled = true;
      }else{
        enabled = false;//集合类型不拷贝
      }
    }
    return enabled;
  }

  private Object getProperty(Object valueObject,String property){
    Object value = null;
    try {
      value = org.apache.commons.beanutils.PropertyUtils.getProperty(valueObject , property);
    } catch (IllegalAccessException e) {
      if(logger.isWarnEnabled()){
        logger.warn(e.getMessage());
      }
    } catch (InvocationTargetException e) {
      if(logger.isWarnEnabled()){
        logger.warn(e.getMessage());
      }
    } catch (NoSuchMethodException e) {
      if(logger.isWarnEnabled()){
        logger.warn(e.getMessage());
      }
    }
    return value;
  }
 
  /**
   * 用于将vo中被赋过值的属性拷贝到po中
   * @param vo
   */
  protected VgEntity autoCopy(VgEntity vo) {
    if(vo.getId() == null){
      setPropertyNullIfNecessary(vo);
      commonDao.store(vo);
      return vo;
    }
    else{
      VgEntity oldEntity = this.get(vo.getClass() , vo.getId());
      try {
        copyProperty(vo , oldEntity);
      } catch (Exception e) {
        e.printStackTrace();
      }
      commonDao.store(oldEntity);
      return oldEntity;
    }
  }
 
  @SuppressWarnings("unchecked")
  protected void filterPropertyNullIfNecessary(Object obj){
    Class beanClass = obj.getClass();
    Field[] fields = extractAllFields(beanClass);
    for (int i = 0; i < fields.length; i++) {
      if(VgEntity.class.isAssignableFrom(fields[i].getType())){
        Object propertyValue = null;
        try {
          propertyValue = Ognl.getValue(fields[i].getName(),obj);
        } catch (OgnlException e) {
          e.printStackTrace();
        }
              if(propertyValue == null){
                continue;
              }else{
                Object idField = null;
          try {
            idField = (Long)Ognl.getValue("id",propertyValue);
          } catch (OgnlException e) {
            e.printStackTrace();
          }
                if(idField == null || idField.equals(0L)){
                  try {
              Ognl.setValue(fields[i].getName(),obj,null);
            } catch (OgnlException e) {
              e.printStackTrace();
            }
                }
              }
      }
    }
  }
 
    @SuppressWarnings("unchecked")
  private void setPropertyNullIfNecessary(Object obj) {
        BeanInfo info = null;
        Class beanClass = obj.getClass();
    try {
      info = Introspector.getBeanInfo(beanClass);
    } catch (IntrospectionException e) {
      e.printStackTrace();
    }
        PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            if (VgEntity.class.isAssignableFrom(descriptors[i].getPropertyType())){
              Object propertyValue = null;
        try {
          propertyValue = Ognl.getValue(descriptors[i].getName(),obj);
        } catch (OgnlException e) {
          e.printStackTrace();
        }
              if(propertyValue == null){
                continue;
              }
              else{
                Object idField = null;
          try {
            idField = (Long)Ognl.getValue("id",propertyValue);
          } catch (OgnlException e) {
            e.printStackTrace();
          }
                if(idField == null || idField.equals(0L)){
                  try {
              Ognl.setValue(descriptors[i].getName(),obj,null);
            } catch (OgnlException e) {
              e.printStackTrace();
            }
                }
              }
            }
        }


  }
   
    @Deprecated
  public void store(VgEntity entity) {
    autoCopy(entity);
  }

  public CommonDao getCommonDao() {
    return commonDao;
  }

  public void setCommonDao(CommonDao commonDao) {
    this.commonDao = commonDao;
  }
 
  public <T extends VgEntity> T load(Class<T> clazz, Long id) {
    T  entity =  commonDao.load(clazz , id);
    return entity;
   
  }
 
  public <T extends VgEntity> T get(Class<T> clazz, Long id) {
    T  entity =  commonDao.get(clazz , id);
//    System.out.println(entity.getId());
    return entity;
   
  }

  public Object exec(Callback callback) throws Exception {
    return callback.exec(commonDao);
  }

  public <T extends VgEntity> List<T> loadAll(Class<T> clazz) {
    return commonDao.loadAll(clazz);
  }

  public void simpleStoreEntity(VgEntity entity) {
    commonDao.store(entity);
  }

  public <T extends VgEntity> List<T> load(Class<T> clazz, List<Long> ids) {
    return commonDao.loadAll(clazz, ids);
  }

  public HibernateTransactionManager getTransactionManager() {
    return transactionManager;
  }

  public void setTransactionManager(HibernateTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
  }

  public SequenceGenerater getSequenceGenerater() {
    if(sequenceGenerater == null){
      sequenceGenerater = (SequenceGenerater)applicationContext.getBean("sequenceGenerater");
    }
    return sequenceGenerater;
  }

  public void setSequenceGenerater(SequenceGenerater sequenceGenerater) {
    this.sequenceGenerater = sequenceGenerater;
  }

  protected TransactionStatus beginTxPropagationRequiresNew(){
    if(transactionManager == null){
      transactionManager = (HibernateTransactionManager)applicationContext.getBean("transactionManager");
    }
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    return transactionManager.getTransaction(definition);
  }
 
  protected void commitTransaction(TransactionStatus transactionStatus){
    if(transactionStatus != null)
      transactionManager.commit(transactionStatus);
  }
 
  protected void rollbackTransaction(TransactionStatus transactionStatus){
    if(transactionStatus != null)
      transactionManager.rollback(transactionStatus);
  }

  public void setApplicationContext(ApplicationContext applicationContext)
      throws BeansException {
    this.applicationContext = applicationContext;
  }


  @Override
  public <T extends VgEntity> void deleteAll(Collection<T> entities) {
  }

  @Override
  public int executeByHql(String hql, String[] paramNames, Object[] values) {
    return 0;
  }

  @Override
  public int executeByHql(String hql, String parameterKey, Object value) {
    return 0;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List findByQuery(String hql, String parameterKey, Object value) {
    return null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List findByQuery(String hql) {
    return null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List findByQuery(String hql, String[] paramNames, Object[] values) {
    return null;
  }

  @Override
  public Object findByQueryUniqueResult(String hql, String[] paramNames,
      Object[] values) {
    return null;
  }

  @Override
  public Object findByQueryUniqueResult(String hql, String parameterKey,
      Object value) {
    return null;
  }

  @Override
  public void initialize(Object object) {
  }

  @Override
  public <T extends VgEntity> List<T> loadAll(Class<T> clazz, Long[] entityIds) {
    return null;
  }

  @Override
  public <T extends VgEntity> List<T> loadAll(Class<T> clazz, List<Long> ids) {
    return null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List query(String hql, Map params) {
    return null;
  }

  @Override
  public void refresh(Object object) {
  }
}
TOP

Related Classes of com.wizriver.dao.DefaultBaseManager

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.