通过数据库DDL反向生成jpa类

satuo20 1年前 ⋅ 450 阅读

java代码

package com.yjzhixue.headless.chrome;

import cn.hutool.core.io.FileUtil;
import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Test {
    public static void main(String[] args) {
//        System.err.println("....");

        String path = "/Users/xiaodx/idea/kp-headless/kp-headless-chrome/src/main/resources/test.sql";
        List<String> lines = FileUtil.readLines(path, "utf-8");
        ClassInfo classInfo = new ClassInfo();

        for (String line :lines) {
            line = line.trim();
//            System.err.println(line);
            if(line.startsWith(")")) {
                if(line.contains("'")) {
                    int firstPos = line.indexOf("'") + 1;
                    classInfo.setComment(line.substring(firstPos, line.indexOf("'", firstPos + 1)));
                }
                break;
            }
            if(line.startsWith("CREATE")) {
                classInfo.setName(line.substring(line.indexOf("TABLE `")+10,line.indexOf("` (")));
                classInfo.setJavaName(getJavaName(classInfo.name, true));
                continue;
            }

            if(line.startsWith("`")) {
                Fs field = new Fs();
                String[] arry = line.split(" ");
                field.setName(arry[0].replace("`", ""));
                field.setJavaName(getJavaName(field.getName(),false));
                field.setTypeDef(arry[1]);

                field.setJavaType(getJavaType(field.getTypeDef()));

                if(line.contains("'")) {
                    int firstPos = line.indexOf("'")+1;
                    field.setComment(line.substring(firstPos,line.indexOf("'",firstPos+1)));
                }
                classInfo.getFs().add(field);
            }
        }

//        System.err.println(JSONUtil.toJsonPrettyStr(classInfo));
        classInfo.print();
    }

    /**
     * @Entity
     * @javax.persistence.Table(name = "t_base_area")
     * @Table(appliesTo = "t_base_area",comment = "省市区") // 有表注释
     * @Data
     * @EntityListeners(AuditingEntityListener.class)
     * public class BaseArea implements Serializable {
     *
     * 	private static final long serialVersionUID = -2260388125919493487L;
     *
     *        @    d	//主键id
     *    @CreatedBy
     *    @Column(columnDefinition="varchar(6) COMMENT '区域ID'")
     * 	private String id;
     *
     *    @Column(columnDefinition="varchar(6) COMMENT '上级区域ID'")
     * 	private String parentId;
     */

    @Data
    static class ClassInfo {
        private String name;
        private String javaName;
        private String comment;
        private List<Fs> fs = new ArrayList<>();

        private void print() {
            StringBuffer buffer = new StringBuffer();
            buffer.append("@javax.persistence.Entity").append("\n");
            buffer.append("@javax.persistence.Table(name = \""+name+"\")").append("\n");
            buffer.append("@org.hibernate.annotations.Table(appliesTo = \""+name+"\",comment = \""+comment+"\")").append("\n");
            buffer.append("@Data").append("\n");
//            buffer.append("@EntityListeners(AuditingEntityListener.class)").append("\n");
            buffer.append("public class "+javaName+" implements Serializable {").append("\n");
            buffer.append("        private static final long serialVersionUID = -2260388125919493487L;").append("\n");


            fs.forEach(f->{
                if(f.getJavaName().equals("id")) {
                    buffer.append("        @Id\n");
                }
                buffer.append("        @Column(columnDefinition=\""+f.typeDef+" COMMENT '"+f.comment+"'\")\n");
                buffer.append("        private ").append(f.javaType).append(" ").append(f.javaName).append(";\n\n");
            });
            buffer.append("}\n");
            System.err.println(buffer);
        }

    }

    @Data
    static class Fs {
        private String name;
        private String javaName;
        private String comment;
        private String typeDef;
        private String javaType;
    }

    private static String getJavaType (String mysqlType) {
        if(mysqlType.startsWith("varchar")) {
            return String.class.getSimpleName();
        }

        if(mysqlType.startsWith("int")) {
            return Integer.class.getSimpleName();
        }

        if(mysqlType.startsWith("bigint")) {
            return Long.class.getSimpleName();
        }
        if(mysqlType.startsWith("decimal")) {
            return BigDecimal.class.getSimpleName();
        }
        if(mysqlType.startsWith("date")) {
            return Date.class.getSimpleName();
        }

        if(mysqlType.startsWith("tinyint")) {
            return Boolean.class.getSimpleName();
        }
        throw new RuntimeException("未知类型"+mysqlType);
    }


    private static String getJavaName(String mysqlName,boolean isClassName) {
        char[] chars = mysqlName.toCharArray();
        StringBuffer buffer = new StringBuffer();
        if(isClassName) {
            buffer.append(mysqlName.substring(0, 1).toUpperCase());
        } else {
            buffer.append(mysqlName.substring(0, 1));
        }
        for (int i = 1; i < chars.length; i++) {
            if(chars[i] == '_') {
                buffer.append((chars[i+1]+"").toUpperCase());
                i = i+1;
            } else {
                buffer.append(chars[i]);
            }
        }
        return buffer.toString();
    }

}

DDL 格式(从nav..中复制出来)

CREATE TABLE `kp_vip_refund` (
  `id` varchar(32) NOT NULL COMMENT '主键',
  `order_id` varchar(32) DEFAULT NULL COMMENT '退款关联订单id',
  `contact_phone` varchar(32) DEFAULT NULL COMMENT '联系电话',
  `contact_people` varchar(50) DEFAULT NULL COMMENT '联系人',
  `apply_refund_time` datetime DEFAULT NULL COMMENT '申请退款时间',
  `apply_refund_by` varchar(32) DEFAULT NULL COMMENT '申请退款人',
  `refund_reason` varchar(100) DEFAULT NULL COMMENT '退款原因',
  `refund_price` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
  `service_opinion` varchar(200) DEFAULT NULL COMMENT '客服意见',
  `refund_status` int(1) DEFAULT NULL COMMENT '退款状态:0=处理中,1=驳回,2=通过,3=取消申请',
  `processing_time` datetime DEFAULT NULL COMMENT '客服处理时间',
  `suggest_refund_price` decimal(10,2) DEFAULT NULL COMMENT '建议退款金额',
  `order_price` decimal(10,2) DEFAULT NULL COMMENT '订单金额',
  `transaction_id` varchar(32) DEFAULT NULL COMMENT '流水号',
  `open_school_time` datetime DEFAULT NULL COMMENT '开学时间',
  PRIMARY KEY (`id`) USING BTREE,
  KEY `idx_order` (`order_id`) USING BTREE,
  KEY `idx_transaction_id` (`transaction_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

全部评论: 0

    我有话说: