依据MySQL表结构生成JFinal Model类的存储过程

房东的猫 提交于 2020-02-29 08:11:40
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;

使用方法

-- 参数databaseName 可以为空,默认使用当前所选数据库
call PROC_Table2Class('databaseName','tableName','package.path')
call PROC_Table2Class('','tableName','package.path')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!