org.beangle.commons.orm.hibernate.RailsNamingStrategy.java Source code

Java tutorial

Introduction

Here is the source code for org.beangle.commons.orm.hibernate.RailsNamingStrategy.java

Source

/* Copyright c 2005-2012.
 * Licensed under GNU  LESSER General Public License, Version 3.
 * http://www.gnu.org/licenses
 */
package org.beangle.commons.orm.hibernate;

import java.io.Serializable;

import org.beangle.commons.lang.Strings;
import org.beangle.commons.orm.TableNamingStrategy;
import org.hibernate.AssertionFailure;
import org.hibernate.cfg.DefaultNamingStrategy;
import org.hibernate.cfg.NamingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Rails????????
 * 
 * @see DefaultNamingStrategy the default strategy
 * @author chaostone
 */
public class RailsNamingStrategy implements NamingStrategy, Serializable {
    private static final long serialVersionUID = -2656604564223895758L;

    private static final Logger logger = LoggerFactory.getLogger(RailsNamingStrategy.class);
    // ???????
    private static final int MaxLength = 30;

    private TableNamingStrategy tableNamingStrategy;

    /**
     * ???(entityName)??
     * 
     * @param className
     */
    public String classToTableName(String className) {
        String tableName = tableNamingStrategy.classToTableName(className);
        if (tableName.length() > MaxLength)
            logger.warn("{}'s length greate than 30!", tableName);
        logger.debug("Mapping entity[{}] to {}", className, tableName);
        return tableName;
    }

    /**
     * ???????
     * 
     * <pre>
     * ???????
     * </re>
     */
    public String tableName(String tableName) {
        return tableName;
    }

    /** ???,?? */
    public String columnName(String columnName) {
        if (columnName.length() > MaxLength)
            logger.warn("{}'s length greate than 30!", columnName);
        return columnName;
    }

    /**
     * ???
     * 
     * <pre>
     * ????????.
     * ??columnName=logicalColumnName
     * </pre>
     */
    public String logicalColumnName(String columnName, String propertyName) {
        return Strings.isNotEmpty(columnName) ? columnName : propertyToColumnName(propertyName);
    }

    /**
     * ?????
     * 
     * <pre>
     * ??.??????
     * ???????(component.name)
     * </pre>
     * 
     * @param propertyName
     */
    public String propertyToColumnName(String propertyName) {
        return addUnderscores(unqualify(propertyName));
    }

    /** Return the argument */
    public String joinKeyColumnName(String joinedColumn, String joinedTable) {
        return columnName(joinedColumn);
    }

    /** Return the property name or propertyTableName */
    public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName,
            String referencedColumnName) {
        String header = null == propertyName ? propertyTableName : unqualify(propertyName);
        if (header == null) {
            throw new AssertionFailure("NamingStrategy not properly filled");
        }
        if (isManyToOne()) {
            header = addUnderscores(header);
        } else {
            header = addUnderscores(propertyTableName);
        }
        return header + "_" + referencedColumnName;

    }

    /** Collection Table */
    public String collectionTableName(String ownerEntity, String ownerEntityTable, String associatedEntity,
            String associatedEntityTable, String propertyName) {
        String ownerTable = null;
        // Just for annotation configuration,it's ownerEntity is classname(not entityName), and
        // ownerEntityTable is class shortname
        if (Character.isUpperCase(ownerEntityTable.charAt(0))) {
            ownerTable = tableNamingStrategy.classToTableName(ownerEntity);
        } else {
            ownerTable = tableName(ownerEntityTable);
        }
        String tblName = tableNamingStrategy.collectionToTableName(ownerEntity, ownerTable, propertyName);
        if (tblName.length() > MaxLength)
            logger.warn("{}'s length greate than 30!", tblName);
        return tblName;
    }

    /**
     * Returns either the table name if explicit or if there is an associated
     * table, the concatenation of owner entity table and associated table
     * otherwise the concatenation of owner entity table and the unqualified
     * property name
     */
    public String logicalCollectionTableName(String tableName, String ownerEntityTable,
            String associatedEntityTable, String propertyName) {
        if (tableName == null) {
            // use of a stringbuilder to workaround a JDK bug
            return new StringBuilder(ownerEntityTable).append("_")
                    .append(associatedEntityTable == null ? unqualify(propertyName) : associatedEntityTable)
                    .toString();
        } else {
            return tableName;
        }
    }

    /**
     * Return the column name if explicit or the concatenation of the property
     * name and the referenced column
     */
    public String logicalCollectionColumnName(String columnName, String propertyName, String referencedColumn) {
        return Strings.isNotEmpty(columnName) ? columnName : unqualify(propertyName) + "_" + referencedColumn;
    }

    public void setTableNamingStrategy(TableNamingStrategy tableNamingStrategy) {
        this.tableNamingStrategy = tableNamingStrategy;
    }

    public TableNamingStrategy getTableNamingStrategy() {
        return tableNamingStrategy;
    }

    protected static String addUnderscores(String name) {
        return Strings.unCamel(name.replace('.', '_'), '_');
    }

    protected static String unqualify(String qualifiedName) {
        int loc = qualifiedName.lastIndexOf('.');
        return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1);
    }

    /**
     * ?ManyToOne
     * 
     * @return
     */
    private boolean isManyToOne() {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        if (trace.length >= 9) {
            for (int i = 6; i <= 8; i++) {
                if (trace[i].getClassName().equals("org.hibernate.cfg.ToOneFkSecondPass"))
                    return true;
            }
        }
        return false;
    }
}