依據MySQL表結構生成JFinal Model類的存儲過程

DROP PROCEDURE IF EXISTS `PROC_Table2Class`;

CREATE ` PROCEDURE `PROC_Table2Class`(IN dbName varchar(50),IN tableName varchar(50) ,IN package varchar(512))
    COMMENT '將錶轉換成JFinal中的model類'
OK:BEGIN

	-- 判斷數據庫和表是否存在
	IF (dbName = '') THEN
		SET dbName = DATABASE();
		SELECT CONCAT('參數"dbName"爲空,默認使用當前所選數據庫[',dbName,']') AS MSG;
	END IF;
	SELECT COUNT(*) INTO @dbExists FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=dbName;
	IF (@dbExists <> 1) THEN
		SELECT CONCAT('數據庫[',tableName,']不存在') as MSG; 
		LEAVE OK;
	END IF;
	
	SELECT COUNT(*),TABLE_COMMENT,CREATE_TIME,UPDATE_TIME INTO @tbExists,@tbComment,@tbCreateTime,@tbLastUpdateTime FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=dbName AND TABLE_NAME=tableName;
	IF (@tbExists <> 1) THEN
		SELECT CONCAT('數據庫[',tableName,']中的表[',tableName,']不存在') as MSG; 
		LEAVE OK;
	END IF;

	IF (package = '') THEN
		SELECT CONCAT('類中的[package]不能爲空') as MSG;
		LEAVE OK;
	END IF;

	-- 將tb_xx_yy轉爲Xxyy
	SELECT LOCATE('_',tableName) INTO @idx;
	SET @clazzName = tableName;
	IF (@idx > 0) THEN
		SET @clazzName = SUBSTRING(@clazzName, @idx + 1, LENGTH(@clazzName));
		SET @clazzName = REPLACE(@clazzName,'_', '');
	END IF;
	-- 去掉尾部的s
	SELECT RIGHT(@clazzName,1) INTO @idx;
	IF (@idx = 's') THEN
		SET @clazzName = SUBSTRING(@clazzName, 1, LENGTH(@clazzName) - 1);
	END IF;

	-- 首字母大寫
	SET @clazzName = CONCAT(UPPER(LEFT(@clazzName,1)), SUBSTRING(@clazzName,2, (LENGTH(@clazzName)-1)));
	
	-- 拼接類
	SELECT CONCAT('package ',package,';\n\nimport com.jfinal.plugin.activerecord.Model;\n\n/**\n* ',@clazzName,'.java \n* 說明:',IF(LENGTH(@tbComment) > 0,@tbComment,'無'),'\n* 建立人: ',user(),'\n* 建立時間:', IFNULL(@tbCreateTime,DATE_FORMAT(NOW(), '%Y-%m-%d %T')),'\n* 最後修改時間:',IFNULL(@tbLastUpdateTime,DATE_FORMAT(NOW(), '%Y-%m-%d %T')),'\n*/\npublic class ', @clazzName,' extends Model<',@clazzName,'> {\n') as MSG
	UNION
	SELECT '	private static final long serialVersionUID = 1L;' as MSG
	UNION
	SELECT CONCAT('	public static final ', @clazzName,' dao = new ',@clazzName,'();\n')
	UNION
	SELECT CONCAT('	/*數據庫表名*/\n	public static final String TABLE_NAME = "',tableName,'";\n	/*如下是數據庫字段*/')
	UNION
	SELECT CONCAT('	public static final String ', COLUMN_NAME,' = "', COLUMN_NAME,'"; //', IF(LENGTH(COLUMN_COMMENT)>0, COLUMN_COMMENT, '註釋無'), ', 數據庫字段類型:', COLUMN_TYPE, IF(IS_NULLABLE='NO', ', 不可爲空', ', 容許爲空')) as MSG 
	FROM information_schema.COLUMNS
	WHERE TABLE_SCHEMA=dbName AND TABLE_NAME=tableName
	UNION 
	SELECT '}'  as MSG;

END;

使用方法java

-- 參數databaseName 能夠爲空,默認使用當前所選數據庫
call PROC_Table2Class('databaseName','tableName','package.path')
call PROC_Table2Class('','tableName','package.path')
相關文章
相關標籤/搜索