在java开发中,不可避免的要碰到根据表生成对应的实体,这个过程是比较机器且繁琐的,我也用过一些逆向工程的工具,比如IDEA自带的生成实体,还有网上开源的工具,用起来也是可以的。
我现在开发用的持久层要不是spring-data-jpa要不就是tk-mybatis,而这两个框架根本都由注解完成数据的CRUD的,这里你只要生成一个实体加上相应的注解就行。
就单单生成实体而言,每次用第三方工具还是感觉太繁琐,总归有一些勾勾选选、启动工程之类的,而且不直观。从根本上看,我们封装的实体就是一些private的属性和getset方法,如果你用了lombok,那就只要属性需要我们写了,这里介绍一种我自己总结的方法:SQL直接生成属性,其它的注解后期加上(一般字段和实体属性都是驼峰或是下划线的,基本不需要注解)
优点:支持自定义扩展,使用方便
下面以PGSQL为例:
效果:
附上源码:
1 select name,type,comment, 2 concat( 3 'private ', 4 case 5 when type like 'character%' and type like '%[]' then 'String[]' 6 when type like 'character%' then 'String' 7 when type like 'timestamp%' then 'Date' 8 else upper(substr(type, 1, 1)) || substr(replace(initcap(replace(type, '_',' ')),' ',''),2) end, 9 ' ', 10 lower(substr(name, 1, 1)) || substr(replace(initcap(replace(name, '_',' ')),' ',''),2), 11 ';', 12 case when comment is null then '' else concat('//',comment) end 13 ) as myField 14 from ( 15 SELECT col_description(a.attrelid,a.attnum) as comment,format_type(a.atttypid,a.atttypmod) as type,a.attname as name 16 FROM pg_class as c,pg_attribute as a where c.relname = 'lead' and a.attrelid = c.oid and a.attnum>0) a
1 2 3 --创建initcap函数 4 create function initcap(ss varchar(1000)) returns varchar(1000) 5 begin 6 declare lena int; 7 declare pos int; 8 declare firsta char(1); 9 declare seconda varchar(999); 10 declare tmpstr varchar(1000); 11 declare retstr varchar(1000); 12 if (length(trim(ss)) = 0) then 13 return ''; 14 end if; 15 if (right(ss,1) != ' ') then 16 set ss=concat(ss,' '); 17 end if; 18 set pos=instr(ss,' '); 19 set lena=length(ss); 20 while (pos > 0) do 21 set tmpstr=trim(left(ss,pos)); 22 set ss = right(ss,lena - pos ); 23 set lena = length(tmpstr); 24 set firsta = upper(left(tmpstr,1)); 25 set seconda = lower(right(tmpstr,lena - 1)); 26 if (length(retstr) > 0) then 27 set retstr = concat(retstr,' ',firsta,seconda); 28 else 29 set retstr = concat(firsta,seconda); 30 end if; 31 set pos = instr(ss,' '); 32 set lena = length(ss); 33 end while; 34 return retstr; 35 end; 36 37 38 --执行生成属性 39 select name,type,comment, 40 concat( 41 'private ', 42 case 43 when type='bigint' then 'Long' 44 when type='varchar' then 'String' 45 when type='int' then 'Integer' 46 when type in('date','datetime','timestamp') then 'Date' 47 else '' end, 48 ' ', 49 concat(lower(substr(name, 1, 1)),substr(replace(initcap(replace(name, '_',' ')),' ',''),2)), 50 ';', 51 if(comment='','',concat('//',comment)) 52 ) as myField 53 from ( 54 select COLUMN_NAME name,DATA_TYPE type,COLUMN_COMMENT comment from INFORMATION_SCHEMA.Columns where table_name='表名') a