标题 :T-SQL 数据表转Java实体类代码(含有字段注释)
declare @TableName sysname = '表名'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'
select @Result = @Result +'
/**
* ' + value + '
**/'+'
private ' + ColumnType + ' ' + ColumnName + ';'+'
'+'public '+ColumnType+' get'+ColumnName+'(){
return '+ColumnName+';
}
public void set'+ColumnName+'('+ColumnType+' o){'+'
this.'+ColumnName+'=o;
}
'
from
(
select replace(col.name, ' ', '_') ColumnName,column_id ColumnId,
value = case when value is not null then CAST(value AS NVARCHAR) else '' end,
case typ.name
when 'bigint' then 'long'
when 'binary' then 'byte[]'
when 'bit' then 'boolean'
when 'char' then 'String'
when 'date' then 'Date'
when 'datetime' then 'Date'
when 'datetime2' then 'Date'
when 'datetimeoffset' then 'Date'
when 'decimal' then 'BigDecimal'
when 'float' then 'float'
when 'image' then 'byte[]'
when 'int' then 'int'
when 'money' then 'BigDecimal'
when 'nchar' then 'String'
when 'ntext' then 'String'
when 'numeric' then 'BigDecimal'
when 'nvarchar' then 'String'
when 'real' then 'double'
when 'smalldatetime' then 'Date'
when 'smallint' then 'short'
when 'smallmoney' then 'BigDecimal'
when 'text' then 'String'
when 'time' then 'Time'
when 'timestamp' then 'Date'
when 'tinyint' then 'byte'
when 'uniqueidentifier' then 'UUID'
when 'varbinary' then 'byte[]'
when 'varchar' then 'String'
else 'UNKNOWN_' + typ.name
end ColumnType,
case
when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
then '?'
else ''
end NullableSign
from sys.columns col join sys.types typ on col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
left JOIN sys.extended_properties prop ON prop.major_id = col.object_id AND prop.minor_id = col.column_id
where object_id = object_id(@TableName)
) t
order by ColumnId
set @Result = @Result + '
}'
print @Result
若上面的sql语句有什么不对的地方,欢迎在评论区指正
参考:
https://www.cnblogs.com/bayes/p/6206297.html
https://www.cnblogs.com/li-lun/p/9441406.html