Java根据实体类转换为sql语句。使用mybatis-plus实现,java实现实体类转sql

Java根据实体类转换为sql语句。使用mybatis-plus实现,java实现实体类转sql

渡星河
2023-04-20 / 0 评论 / 9 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年04月20日,已超过517天没有更新,若内容或图片失效,请留言反馈。

必要依赖

<!-- MyBatis-Plus -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

工具类SQLGenerator

package cn.yyx.aclservice;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

public class SQLGenerator {

    public static String generateDDL(Class<?> clazz) {
        StringBuilder sb = new StringBuilder();
        String tableName = getTableName(clazz);
        sb.append("CREATE TABLE `").append(tableName).append("` (\n");
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            sb.append(getColumnDefinition(field));
            sb.append(",\n");
        }
        sb.append("PRIMARY KEY (`id`)\n")
                .append(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='")
                .append(tableName).append("';");
        return sb.toString();
    }

    private static String getTableName(Class<?> clazz) {
        String tableName = clazz.getSimpleName();
        TableName table = clazz.getAnnotation(TableName.class);
        if (table != null && !"".equals(table.value())) {
            tableName = table.value();
        }
        return tableName;
    }

    private static String getColumnDefinition(Field field) {
        StringBuilder sb = new StringBuilder();
        String columnName = getColumnName(field);
        Class<?> type = field.getType();
        String columnType = getColumnType(type);
        if (columnType != null && !"".equals(columnType)) {
            sb.append("`").append(columnName).append("` ").append(columnType)
                    .append(" DEFAULT NULL COMMENT '").append(getColumnComment(field)).append("'");
        }
        return sb.toString();
    }

    private static String getColumnName(Field field) {
        String columnName = field.getName();
        TableField tableField = field.getAnnotation(TableField.class);
        if (tableField != null && !"".equals(tableField.value())) {
            columnName = tableField.value();
        }
        return columnName;
    }

    private static String getColumnComment(Field field) {
        String columnComment = "";
        ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
        if (apiModelProperty != null && !"".equals(apiModelProperty.value())) {
            columnComment = apiModelProperty.value();
        }
        return columnComment;
    }

    private static String getColumnType(Class<?> type) {
        if (String.class.equals(type)) {
            return "VARCHAR(255)";
        } else if (Integer.class.equals(type) || int.class.equals(type)) {
            return "INT(11)";
        } else if (Long.class.equals(type) || long.class.equals(type)) {
            return "BIGINT(20)";
        } else if (BigDecimal.class.equals(type)) {
            return "DECIMAL(10,2)";
        } else if (Boolean.class.equals(type) || boolean.class.equals(type)) {
            return "TINYINT(1)";
        } else if (Double.class.equals(type) || double.class.equals(type)) {
        return "DOUBLE(10,2)";
        }
        else if (Date.class.equals(type)) {
            return "DATETIME";
        } else {
            return null;
        }
    }

}

实体类

package cn.yyx.order.entity;

import java.math.BigDecimal;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 *
 * </p>
 *
 * @author 渡星河
 * @since 2023-04-18
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("t_order")
@ApiModel(value="Order对象", description="")
@HeadRowHeight(20)
@ColumnWidth(20)
@ContentRowHeight(15)
@AllArgsConstructor
@NoArgsConstructor
public class Order implements Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    @ExcelProperty(index = 0,value = "客户名")
    private String cname;
    @ExcelProperty(index = 1,value = "性别")
    private String sex;
    @ExcelProperty(index = 2,value = "业务名字")
    private String sname;
    @ExcelProperty(index = 3,value = "技术名字")
    private String operatorName;
    @ExcelProperty(index = 4,value = "手机号")
    private String phone;
    @ExcelProperty(index = 5,value = "项目名字")
    private String itemName;
    @ExcelProperty(index = 6,value = "销售人员的编号")
    @ApiModelProperty(value = "销售人员的编号")
    private String saleId;
    @ExcelProperty(index = 7,value = "技术人员的编号")
    @ApiModelProperty(value = "技术人员的编号")
    private String operatorId;
    @ExcelProperty(index = 8,value = "订单日期")
    @ApiModelProperty(value = "订单日期")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date orderDate;
    @ExcelProperty(index = 9,value = "服务状态")
    @ApiModelProperty(value = "0 已经服务 1 服务中 2 交了定金 3 退款")
    private Integer orderStatus;
    @ExcelProperty(index = 10,value = "是否删除")
    @TableLogic(value = "1",delval = "0")
    private Integer delstatus;
    @ExcelProperty(index = 11,value = "单价")
    private Double orderPrice;
    @ExcelProperty(index = 12,value = "备注")
    @ApiModelProperty(value = "备注")
    private String note;
    @JsonFormat(pattern = "yyyy-MM-dd")
    @ExcelProperty(index = 13,value = "客户生日")
    private Date birthDay;
}

测试类

package cn.yyx.aclservice;

import cn.yyx.employee.entity.Employee;
import cn.yyx.order.entity.Order;

public class Test {
    public static void main(String[] args) {
        String ddl = SQLGenerator.generateDDL(Order.class);
        System.out.println(ddl);
    }
}

输出结果

CREATE TABLE `t_order` (
`serialVersionUID` BIGINT(20) DEFAULT NULL COMMENT '',
`id` VARCHAR(255) DEFAULT NULL COMMENT '',
`cname` VARCHAR(255) DEFAULT NULL COMMENT '',
`sex` VARCHAR(255) DEFAULT NULL COMMENT '',
`sname` VARCHAR(255) DEFAULT NULL COMMENT '',
`operatorName` VARCHAR(255) DEFAULT NULL COMMENT '',
`phone` VARCHAR(255) DEFAULT NULL COMMENT '',
`itemName` VARCHAR(255) DEFAULT NULL COMMENT '',
`saleId` VARCHAR(255) DEFAULT NULL COMMENT '销售人员的编号',
`operatorId` VARCHAR(255) DEFAULT NULL COMMENT '技术人员的编号',
`orderDate` DATETIME DEFAULT NULL COMMENT '订单日期',
`orderStatus` INT(11) DEFAULT NULL COMMENT '0 已经服务 1 服务中 2 交了定金 3 退款',
`delstatus` INT(11) DEFAULT NULL COMMENT '',
`orderPrice` DOUBLE(10,2) DEFAULT NULL COMMENT '',
`note` VARCHAR(255) DEFAULT NULL COMMENT '备注',
`birthDay` DATETIME DEFAULT NULL COMMENT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='t_order';
1

评论 (0)

取消