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

cn.sylinx.hbatis.ext.model.Model Maven / Gradle / Ivy

There is a newer version: 2.0.0.RELEASE
Show newest version
package cn.sylinx.hbatis.ext.model;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import cn.sylinx.hbatis.db.mapper.ModelBuilder;
import cn.sylinx.hbatis.exception.HbatisException;

@SuppressWarnings({ "unchecked", "serial" })
public class Model implements Serializable, Cloneable {

	private static final String NULLABLE_FIELDS = "NULLABLE_FIELDS";
	/**
	 * 自定义属性
	 */
	private Map context = new HashMap();

	public Map getContext() {
		return context;
	}

	/**
	 * 对应属性可设置为空
	 * 
	 * @param attributeName
	 * @return
	 */
	public  T withNullable(String attributeName) {
		getNullableFields().add(attributeName);
		return (T) this;
	}

	/**
	 * 对应属性可设置为空
	 * 
	 * @param attributeNames
	 * @return
	 */
	public  T withNullables(String... attributeNames) {
		if (attributeNames != null) {
			for (String attributeName : attributeNames) {
				getNullableFields().add(attributeName);
			}
		}
		return (T) this;
	}

	/**
	 * 清空可空字段
	 * 
	 * @return
	 */
	public  T removeNullable() {
		getNullableFields().clear();
		return (T) this;
	}

	/**
	 * 将所有字段可设置为空
	 * 
	 * @return
	 */
	public  T withNullable() {
		List fieldList = ModelBuilder.getObjectAllFields(this.getClass());
		for (Field f : fieldList) {
			withNullable(f.getName());
		}
		return (T) this;
	}

	/**
	 * 获取所有可设置空字段
	 * 
	 * @return
	 */
	public Set getNullableFields() {
		Object object = context.get(NULLABLE_FIELDS);
		if (object == null) {
			object = new HashSet();
			context.put(NULLABLE_FIELDS, object);
		}

		return (Set) object;
	}

	@Override
	public Object clone() {

		Model cloneObject = null;
		try {
			cloneObject = (Model) super.clone();
		} catch (CloneNotSupportedException e) {
			throw new HbatisException(e);
		}

		if (cloneObject != null) {
			cloneObject.context = new HashMap();
			// 深度克隆 context
			Iterator> iterator = context.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry entry = iterator.next();
				cloneObject.context.put(entry.getKey(), entry.getValue());
			}
		}

		return cloneObject;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy