com.greenline.hrs.admin.util.db.SchemaExport.java Source code

Java tutorial

Introduction

Here is the source code for com.greenline.hrs.admin.util.db.SchemaExport.java

Source

/*
 * Project: admin-parent
 * 
 * File Created at 2014-04-03
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.hrs.admin.util.db;

import com.greenline.hrs.admin.util.string.StringUtil;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author July
 * @version V1.0
 * @type SchemaExport
 * @desc
 * @date 2014-04-03
 */
public class SchemaExport {

    private static final String LINUX_LINE_DELIMITER = "\n";

    /**
     * ??
     */
    private SchemaExport() {
        super();
    }

    public static String exportMySQL(Class type) {
        if (type == null) {
            return StringUtils.EMPTY;
        }
        String tableName = type.getName().substring(type.getName().lastIndexOf('.') + 1);
        tableName = StringUtil.underscoreName(tableName);
        StringBuilder sb = new StringBuilder();
        sb.append("DROP TABLE IF EXISTS `" + tableName + "`;" + LINUX_LINE_DELIMITER);
        sb.append("CREATE TABLE `");
        sb.append(tableName);
        sb.append("` (" + LINUX_LINE_DELIMITER + LINUX_LINE_DELIMITER);
        sb.append("`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '',");
        Field[] fields = type.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                sb.append("`" + StringUtil.underscoreName(field.getName()) + "` "
                        + JdbcColumnUtil.getColumeTypeDesc(field.getType()) + " NOT NULL COMMENT '',"
                        + LINUX_LINE_DELIMITER);
            }
        }
        sb.append("PRIMARY KEY (`id`)" + LINUX_LINE_DELIMITER);
        sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        return sb.toString();
    }

}