All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.fingertip.simpledao.utils.ModelUtil Maven / Gradle / Ivy

The newest version!
package org.fingertip.simpledao.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.fingertip.simpledao.annotation.Id;
import org.fingertip.simpledao.annotation.Table;
import org.fingertip.simpledao.bean.ModelClassMessage;
import org.fingertip.simpledao.enums.ExecuteType;
import org.fingertip.simpledao.exception.DaoException;

public class ModelUtil {
    
    /**
     * 获取表名
     * @param 
     * @return
     * @throws DaoException
     */
    public static  String getTableName(Class entityClass) throws DaoException {
    	DaoException exception = new DaoException("未定义表");
    	if(entityClass == null){
    		throw new NullPointerException("实体类为空");
    	}
    	Table table = entityClass.getAnnotation(Table.class);
		String value;
    	if(table != null){
			value = table.value();
			if(value == null || "".equals(value)){
				throw exception;
			}
    	}else{
			String simpleName = entityClass.getSimpleName();
			value = formatName(simpleName);
		}

    	return value;
	}
	
	/**
	 * 获取模型类的相关信息
	 * @param entityClass
	 * @param executeType
	 * @return
	 * @throws DaoException
	 */
    public static  ModelClassMessage getModelClassMessage(Class entityClass,ExecuteType executeType) throws DaoException{
    	ModelClassMessage message = new ModelClassMessage();
    	if(entityClass == null){
    		throw new NullPointerException("实体类为空");
    	}
    	if(executeType != ExecuteType.EXECUTE_TYPE_SELECT_SQL){
    		String tableName = null;
    		try {
    			tableName = ModelUtil.getTableName(entityClass);
			} catch (Exception e) {
				if(executeType != ExecuteType.EXECUTE_TYPE_SELECT_ENTITY){
					throw e;
				}
			}
    		message.setTableName(tableName);
    	}
    	
    	//获取字段信息
    	Map dbEntityFieldNames = new HashMap<>();
    	Map entityDbFieldNames = new HashMap<>();
    	Map dbFields = new HashMap<>();
    	Map entityFields = new HashMap<>();
    	List fields = new ArrayList<>();
    	try {
	    	//子类参数
	    	Field[] childFields = entityClass.getDeclaredFields();
	    	if(childFields != null && childFields.length > 0){
	    		fields.addAll(Arrays.asList(childFields));
	    	}
			//父类参数
			Class objClass = entityClass.getClass().getSuperclass();//第一个父类
			for(;objClass != Object.class;objClass = objClass.getSuperclass()){
				Field[] superFields = objClass.getDeclaredFields();
				fields.addAll(Arrays.asList(superFields));
			}
		}catch (Exception e){}
    	
    	for(Field field :fields){
    		
    		if(field.getModifiers() != Modifier.PRIVATE){
    			continue;
    		}
    		org.fingertip.simpledao.annotation.Field anno = field.getAnnotation(org.fingertip.simpledao.annotation.Field.class);
    		String annoName = null;
    		String finalFieldName = null;
    		boolean specially = false;
    		if(anno != null){
    			if(executeType == ExecuteType.EXECUTE_TYPE_INSERT){
    				if(anno.ignoreInsert()){
    					continue;
    				}
    			}else if(executeType == ExecuteType.EXECUTE_TYPE_UPDATE){
    				if(anno.ignoreUpdate()){
    					continue;
    				}
    			}
    			annoName = anno.name();
    			if(annoName == null || annoName.equals("")){
    				finalFieldName = field.getName();
    			}else {
    				finalFieldName = annoName;
    				specially = true;
    			}
    		} 
    		
    		if(finalFieldName == null){
    			finalFieldName = field.getName();
    		}
    		
    		if(!specially){
				finalFieldName = formatName(finalFieldName);
    		}
    		dbEntityFieldNames.put(finalFieldName, field.getName());
    		entityDbFieldNames.put(field.getName(), finalFieldName);
    		dbFields.put(finalFieldName, field);
    		entityFields.put(field.getName(), field);
    		
    		Id id = field.getAnnotation(Id.class);
    		if(id != null){
    			message.setIdName(finalFieldName);
    		}
    	}
    	
    	if(dbEntityFieldNames.isEmpty()){
    		throw new DaoException("查询字段不明确");
    	}
    	message.setDbEntityFieldNames(dbEntityFieldNames);
    	message.setEntityDbFieldNames(entityDbFieldNames);
    	message.setDbFields(dbFields);
    	message.setEntityFields(entityFields);
    	return message;
    }

    /**
     * 实体转为参数数组的集合
     * 	一个实体对应集合的一个元素(参数数组数组)
     * @param entities
     * @param fieldNames
     * @param entityClass
     * @return
     */
    public static  List entityToArgsList(List entities,Collection fieldNames,Class entityClass){
    	List argsList = new ArrayList<>();
    	for(Object entity : entities){
    		if(entity == null){
    			throw new NullPointerException("实体类为空");
    		}
    		List args = new ArrayList<>();
    		for(String name : fieldNames){
				entityToArgs(args, entity, name, entityClass);
    		}
    	}
    	return argsList;
    }
    
    /**
     * 实体转为参数数组的
     * 	所有参数放到一个数组里面
     * @param entities
     * @param fieldNames
     * @param entityClass
     * @return
     */
    public static  Object[] entityToArgs(List entities,Collection fieldNames,Class entityClass){
    	List args = new ArrayList<>();
    	for(Object entity : entities){
    		if(entity == null){
    			throw new NullPointerException("实体类为空");
    		}
			for(String name : fieldNames) {
				entityToArgs(args, entity, name, entityClass);
			}
    	}
    	return args.toArray();
    }

    public static  void entityToArgs(List args,Object entity,String name,Class entityClass){
		try {
			Field field = entityClass.getDeclaredField(name);
			if(field != null){
				field.setAccessible(true);
				Object value = field.get(entity);
				args.add(value);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 格式化名称
	 * 不是指定的表名或字段名,则将字段名中的大写字母转小写,并在前面加“_”
	 * @param name
	 * @return
	 */
	public static String formatName(String name){
		Pattern pattern = Pattern.compile("[A-Z]");
		Matcher matcher = pattern.matcher(name);
		boolean find = matcher.find();
		if(find){
			StringBuilder builder = new StringBuilder();
			char[] chars = name.toCharArray();
			for(int i = 0;i < chars.length;i++){
				char c = chars[i];
				if(Character.isUpperCase(c)){
					if(i != 0){
						builder.append("_");
					}
					builder.append(String.valueOf(c).toLowerCase());
				}else{
					builder.append(c);
				}
			}
			return builder.toString();
		}
		return name;
	}


	/**
	 * 获取id值
	 * @param entity
	 * @param entityClass
	 * @param message
	 * @param idName
	 * @param 
	 * @return
	 */
	public static  Object getIdVal(Object entity,Class entityClass,ModelClassMessage message,String idName){
		try {
			Map fieldNameMap = message.getEntityDbFieldNames();
			Field idField = entityClass.getDeclaredField(fieldNameMap.get(idName));
			idField.setAccessible(true);
			return idField.get(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}