SQL直接生成实体属性,简单粗暴型

在java开发中,不可避免的要碰到根据表生成对应的实体,这个过程是比较机器且繁琐的,我也用过一些逆向工程的工具,比如IDEA自带的生成实体,还有网上开源的工具,用起来也是可以的。

我现在开发用的持久层要不是spring-data-jpa要不就是tk-mybatis,而这两个框架根本都由注解完成数据的CRUD的,这里你只要生成一个实体加上相应的注解就行。

就单单生成实体而言,每次用第三方工具还是感觉太繁琐,总归有一些勾勾选选、启动工程之类的,而且不直观。从根本上看,我们封装的实体就是一些private的属性和get\set方法,如果你用了lombok,那就只要属性需要我们写了,这里介绍一种我自己总结的方法:SQL直接生成属性,其它的注解后期加上(一般字段和实体属性都是驼峰或是下划线的,基本不需要注解)

优点:支持自定义扩展,使用方便   

下面PGSQL为例:

效果:

附上源码:

select name,type,comment,
concat(
'private ',
case 
when type like 'character%' and type like '%[]' then 'String[]' 
when type like 'character%' then 'String' 
when type like 'timestamp%' then 'Date' 
else upper(substr(type, 1, 1)) || substr(replace(initcap(replace(type, '_',' ')),' ',''),2) end,
' ',
lower(substr(name, 1, 1)) || substr(replace(initcap(replace(name, '_',' ')),' ',''),2),
';',
case when comment is null then '' else concat('//',comment) end
) as myField 
from (
SELECT col_description(a.attrelid,a.attnum) as comment,format_type(a.atttypid,a.atttypmod) as type,a.attname as name   
FROM pg_class as c,pg_attribute as a where c.relname = 'lead' and a.attrelid = c.oid and a.attnum>0) a

MYSQL版

mysql没有initcap函数,可以自定义一个


--创建initcap函数
create function initcap(ss varchar(1000)) returns varchar(1000)
begin
declare lena int;
declare pos int;
declare firsta char(1);
declare seconda varchar(999);
declare tmpstr varchar(1000);
declare retstr varchar(1000);
if (length(trim(ss)) = 0) then
   return '';
end if;
if (right(ss,1) != ' ') then
    set ss=concat(ss,' ');
end if;
set pos=instr(ss,' ');
set lena=length(ss);
while (pos > 0) do
   set tmpstr=trim(left(ss,pos));
   set ss = right(ss,lena - pos );
   set lena = length(tmpstr);
   set firsta = upper(left(tmpstr,1));
   set seconda = lower(right(tmpstr,lena - 1));
   if (length(retstr) > 0) then
       set retstr = concat(retstr,' ',firsta,seconda);
   else
       set retstr = concat(firsta,seconda);
   end if;
   set pos = instr(ss,' ');
   set lena = length(ss);
end while;
return retstr;
end;


--执行生成属性
select name,type,comment,
concat(
'private ',
case 
when type='bigint' then 'Long' 
when type='varchar' then 'String' 
when type='int' then 'Integer' 
when type in('date','datetime','timestamp') then 'Date'  
else '' end,
' ',
concat(lower(substr(name, 1, 1)),substr(replace(initcap(replace(name, '_',' ')),' ',''),2)),
';',
if(comment='','',concat('//',comment))
) as myField 
from (
select COLUMN_NAME name,DATA_TYPE type,COLUMN_COMMENT comment from INFORMATION_SCHEMA.Columns where table_name='表名') a

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值