net.ymate.platform.persistence.support.EntityMeta.java Source code

Java tutorial

Introduction

Here is the source code for net.ymate.platform.persistence.support.EntityMeta.java

Source

/*
 * Copyright 2007-2107 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.ymate.platform.persistence.support;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.ymate.platform.base.YMP;
import net.ymate.platform.commons.i18n.I18N;
import net.ymate.platform.commons.lang.PairObject;
import net.ymate.platform.commons.util.ClassUtils;
import net.ymate.platform.persistence.annotation.Entity;
import net.ymate.platform.persistence.annotation.Id;
import net.ymate.platform.persistence.annotation.PK;
import net.ymate.platform.persistence.annotation.Property;
import net.ymate.platform.persistence.base.IEntity;
import net.ymate.platform.persistence.base.IEntityPK;

import org.apache.commons.lang.StringUtils;

/**
 * <p>
 * EntityMeta
 * </p>
 * <p>
 * 
 * </p>
 * 
 * @author (suninformation@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">?</th><th width="100px"></th><th
 *          width="100px"></th><th width="100px"></th>
 *          </tr>
 *          <!--  Table ?? -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td></td>
 *          <td></td>
 *          <td>2014216?2:20:48</td>
 *          </tr>
 *          </table>
 */
public class EntityMeta {

    private String __tableName;
    private Class<?> __primaryKeyClass;
    private List<String> __primaryKeys = new ArrayList<String>();
    private List<String> __autoIncrementColumns = new ArrayList<String>();
    private Map<String, ColumnInfo> __columnMap = new HashMap<String, ColumnInfo>();
    //
    private boolean __isCompositeKey;
    //
    private boolean __isSimple;
    //

    /**
     * ????
     */
    private List<String> __fieldSet = new ArrayList<String>();

    /**
     * ?Bean
     */
    private Map<String, String> __classAttributeMap = new HashMap<String, String>();

    /**
     * 
     * 
     * @param entityClass 
     * @param prefix ?
     */
    public EntityMeta(Class<?> entityClass, String prefix) {
        this(entityClass, prefix, false);
    }

    /**
     * 
     * @param entityClass 
     * @param prefix ?
     * @param simple ??trueentityClass???
     */
    public EntityMeta(Class<?> entityClass, String prefix, boolean simple) {
        if (simple) {
            this.__isSimple = true;
            this.__init(entityClass);
        } else {
            // ???
            if (!ClassUtils.isInterfaceOf(entityClass, IEntity.class)) {
                throw new RuntimeException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                        "ymp.jdbc.entity_class_need_impl", entityClass.getName()));
            }
            Entity t = entityClass.getAnnotation(Entity.class);
            if (null != t) {
                this.__tableName = StringUtils.defaultIfBlank(prefix, "") + t.name();
                this.__init(entityClass);
            } else {
                throw new RuntimeException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                        "ymp.jdbc.entity_class_need_anno_table", entityClass.getName()));
            }
        }
    }

    /**
     * ?
     * 
     * TODO ???name????
     * <p>?DAO????NULL</p>
     */
    private void __init(Class<?> entityClass) {
        // @Column
        for (Field _f : ClassUtils.getFields(entityClass, true)) {
            Property _c = _f.getAnnotation(Property.class);
            if (_c != null) {
                this.getColumnMap().put(_c.name(), new ColumnInfo(_c.name(), _f.getName(), _c.defaultValue(),
                        _c.isAutoIncrement(), _c.sequenceName()));
                String _cName = StringUtils.defaultIfEmpty(_c.name(), _f.getName());
                this.getColumnNames().add(_cName);
                this.getClassAttributeMap().put(_cName, buildFieldNameToClassAttribute(_cName));
                if (_c.isAutoIncrement()) {
                    this.__autoIncrementColumns.add(_cName);
                }
            }
        }
        if (!this.__isSimple) {
            // @Id
            List<PairObject<Field, Id>> _results = ClassUtils.getFieldAnnotations(entityClass, Id.class, true);
            if (_results.size() > 0) {
                Field _idF = _results.get(0).getKey();
                this.__primaryKeyClass = _idF.getType();
                PK _pk = _idF.getType().getAnnotation(PK.class);
                if (_pk != null) {
                    // ???
                    if (!ClassUtils.isInterfaceOf(_idF.getType(), IEntityPK.class)) {
                        throw new RuntimeException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                                "ymp.jdbc.entity_class_need_entitypk", entityClass.getName()));
                    }
                    this.__isCompositeKey = true;
                    for (Field _pkF : ClassUtils.getFields(_idF.getType(), true)) {
                        // PK @Column
                        Property _pkC = _pkF.getAnnotation(Property.class);
                        if (_pkC != null) {
                            this.getColumnMap().put(_pkC.name(), new ColumnInfo(_pkC.name(), _pkF.getName(),
                                    _pkC.defaultValue(), _pkC.isAutoIncrement(), _pkC.sequenceName()));
                            String _cName = StringUtils.defaultIfEmpty(_pkC.name(), _pkF.getName());
                            this.getColumnNames().add(_cName);
                            this.getClassAttributeMap().put(_cName, buildFieldNameToClassAttribute(_cName));
                            this.getPrimaryKeys().add(_cName);
                            if (_pkC.isAutoIncrement()) {
                                this.__autoIncrementColumns.add(_cName);
                            }
                        }
                    }
                } else {
                    Property _idC = _idF.getAnnotation(Property.class);
                    if (_idC != null) {
                        this.getPrimaryKeys().add(StringUtils.defaultIfEmpty(_idC.name(), _idF.getName()));
                    }
                }
            }
            //
            if (this.getPrimaryKeys().isEmpty()) {
                throw new RuntimeException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                        "ymp.jdbc.entity_class_need_anno_id", entityClass.getName()));
            }
        }
    }

    /**
     * @return the __isSimple
     */
    public boolean isSimple() {
        return __isSimple;
    }

    /**
     * @return the tableName
     */
    public String getTableName() {
        return this.__tableName;
    }

    /**
     * @return the primaryKeys
     */
    public List<String> getPrimaryKeys() {
        return __primaryKeys;
    }

    /**
     * @param columnName ??
     * @return  columnName ??
     */
    public boolean isAutoIncrementColumn(String columnName) {
        return this.__autoIncrementColumns.contains(columnName);
    }

    /**
     * @return ??
     */
    public boolean hasAutoIncrementColumn() {
        return this.__autoIncrementColumns.size() > 0;
    }

    /**
     * @return the columnMap
     */
    public Map<String, ColumnInfo> getColumnMap() {
        return __columnMap;
    }

    /**
     * @return @Column?????
     */
    public List<String> getColumnNames() {
        return this.__fieldSet;
    }

    /**
     * @return ?Bean
     */
    public Map<String, String> getClassAttributeMap() {
        return this.__classAttributeMap;
    }

    /**
     * @return ????
     */
    public boolean isCompositeKey() {
        return this.__isCompositeKey;
    }

    /**
     * @return ?
     */
    public Class<?> getPrimaryKeyClass() {
        return this.__primaryKeyClass;
    }

    /**
     * ????JavaBean?<br/>
     * ??"user_name"?"UserName"<br/>
     * @param fieldName ??
     * @return ?JavaBean?
     */
    public static String buildFieldNameToClassAttribute(String fieldName) {
        if (StringUtils.contains(fieldName, '_')) {
            String[] _words = StringUtils.split(fieldName, '_');
            if (_words != null) {
                if (_words.length > 1) {
                    StringBuilder _returnBuilder = new StringBuilder();
                    for (String _word : _words) {
                        _returnBuilder.append(StringUtils.capitalize(_word.toLowerCase()));
                    }
                    return _returnBuilder.toString();
                } else {
                    return StringUtils.capitalize(_words[0].toLowerCase());
                }
            }
        }
        return fieldName;
    }

    /**
     * <p>
     * ColumnInfo
     * </p>
     * <p>
     * 
     * </p>
     * 
     * @author (suninformation@163.com)
     * @version 0.0.0
     *          <table style="border:1px solid gray;">
     *          <tr>
     *          <th width="100px">?</th><th width="100px"></th><th
     *          width="100px"></th><th width="100px"></th>
     *          </tr>
     *          <!--  Table ?? -->
     *          <tr>
     *          <td>0.0.0</td>
     *          <td></td>
     *          <td></td>
     *          <td>2011-10-8?11:19:57</td>
     *          </tr>
     *          </table>
     */
    public class ColumnInfo {

        private String columnName;
        private String fieldName;
        private boolean autoIncrement;
        private String sequenceName;
        private String defaultValue;

        /**
         * 
         */
        public ColumnInfo() {
        }

        /**
         * 
         * @param columnName
         * @param fieldName
           * @param defaultValue
         * @param autoIncrement
         * @param sequenceName
         */
        public ColumnInfo(String columnName, String fieldName, String defaultValue, boolean autoIncrement,
                String sequenceName) {
            this.columnName = columnName;
            this.fieldName = fieldName;
            this.defaultValue = defaultValue;
            this.autoIncrement = autoIncrement;
            this.sequenceName = sequenceName;
        }

        public String getColumnName() {
            return columnName;
        }

        public void setColumnName(String columnName) {
            this.columnName = columnName;
        }

        public String getFieldName() {
            return fieldName;
        }

        public void setFieldName(String fieldName) {
            this.fieldName = fieldName;
        }

        public boolean isAutoIncrement() {
            return autoIncrement;
        }

        public void setAutoIncrement(boolean autoIncrement) {
            this.autoIncrement = autoIncrement;
        }

        public String getSequenceName() {
            return sequenceName;
        }

        public void setSequenceName(String sequenceName) {
            this.sequenceName = sequenceName;
        }

        public String getDefaultValue() {
            return defaultValue;
        }

        public void setDefaultValue(String defaultValue) {
            this.defaultValue = defaultValue;
        }
    }

}