欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatisplus代码生成器使用(java代码生成工具)

程序员文章站 2023-11-20 23:43:46
前言:原本想使用autogenerator 是 mybatis-plus 的官方代码生成器 ,尝试了一下,竟然报错,原因可能是mybatis-plus和mybatis-plus-generator 的...

前言:

原本想使用autogenerator 是 mybatis-plus 的官方代码生成器 ,尝试了一下,竟然报错,原因可能是mybatis-plus和mybatis-plus-generator 的版本不一致,因为我用的mybatis-plus 的版本是3.42 ,但是mybatis-plus-generator的3.4.2不知道怎么了,下载不下来,只能下载3.4.1,发现运行起来老是报错,还有一堆配置说明要看,于是自己手写生成代码的工具类,觉得更简单些。分享给大家,请多多指教。

pom文件引入java-mysql 驱动依赖

<dependency>

<groupid>mysql</groupid>

<artifactid>mysql-connector-java</artifactid>

<version>8.0.22</version>

</dependency>

单类代码实现,复制粘贴到编辑器里,主方法运行即可。

import org.apache.commons.lang3.stringutils;

import java.io.file;

import java.io.fileoutputstream;

import java.sql.connection;

import java.sql.databasemetadata;

import java.sql.drivermanager;

import java.sql.resultset;

import java.text.simpledateformat;

import java.util.date;

/**

* mybatis plus通用生成工具

* 可生成业务接口、mapper接口、实体类

*

* @author tarzan liu

* @date 2021/4/10 19:44

*/

public class mybatisplustools {

private static final string driver = “com.mysql.cj.jdbc.driver”;//驱动

private static final string user = “root”; //数据库账号

private static final string pwd = “123456”; //数据库密码

private static final string url = “
jdbc:mysql://127.0.0.1:3306/ofcms” + “?user=” + user + “&password=” + pwd+”&useunicode=true&characterencoding=utf-8&zerodatetimebehavior=converttonull”; //链接参数

private static string tablename = “of_cms_ad”; // 数据库表名

private static string aliasname = “cms_ad”; // 数据库别名,可以与数据库表名相同

private static final string packagepath = “com/tarzan/cms”; //mapper.xml命名空间路径

private static final string packagename = “com.tarzan.cms”; //mapper.xml命名空间路径

private static final string author = “tarzan”; // 作者

private static final string rootpathname = “src/main/java/”; // 默认生成主文件夹路径

private static connection getconnection = null;

static simpledateformat format = new simpledateformat(“yyyy-mm-dd hh:mm:ss”);

/**

* 链接数据库

*/

private static connection getconnections() {

try {

class.forname(driver);

getconnection = drivermanager.getconnection(url);

} catch (exception e) {

e.printstacktrace();

}

return getconnection;

}

/**

* 格式化默认值

*/

private static string defaultvalue(string value) {

if (stringutils.isnotblank(value)) {

return “;默认值:” + value;

}

{

return “”;

}

}

private static string getaliasname(string tablename,string prefix){

return tablename.substring(prefix.length());

}

/**

* 格式化数据类型

* 返回的是基本类型的包装类

* 如果使用基本数据类型long

*/

private static string formattype(string typevalue) {

if (“bit”.equalsignorecase(typevalue)) {

return “boolean”;

}

else if (

typevalue.equalsignorecase(“int”) || typevalue.equalsignorecase(“int unsigned”)

|| typevalue.equalsignorecase(“tinyint”) || typevalue.equalsignorecase(“tinyint unsigned”)

|| typevalue.equalsignorecase(“smallint”) || typevalue.equalsignorecase(“smallint unsigned”)

|| typevalue.equalsignorecase(“mediumint”) || typevalue.equalsignorecase(“mediumint unsigned”)

) {

return “integer”;

} else if (typevalue.equalsignorecase(“bigint”) || typevalue.equalsignorecase(“bigint unsigned”)) {

return “long”;

} else if (typevalue.equalsignorecase(“float”) || typevalue.equalsignorecase(“float unsigned”)) {

return “float”;

} else if (typevalue.equalsignorecase(“decimal”) || typevalue.equalsignorecase(“decimal unsigned”) || typevalue.equalsignorecase(“numeric”) || typevalue.equalsignorecase(“numeric unsigned”)

|| typevalue.equalsignorecase(“real”) || typevalue.equalsignorecase(“real unsigned”) || typevalue.equalsignorecase(“money”) || typevalue.equalsignorecase(“money unsigned”)

|| typevalue.equalsignorecase(“smallmoney”) || typevalue.equalsignorecase(“smallmoney unsigned”)) {

return “double”;

} else if (typevalue.equalsignorecase(“varchar”) || typevalue.equalsignorecase(“char”)

|| typevalue.equalsignorecase(“nvarchar”) || typevalue.equalsignorecase(“nchar”)

|| typevalue.equalsignorecase(“text”)) {

return “string”;

} else if (typevalue.equalsignorecase(“datetime”)) {

return “date”;

} else if (typevalue.equalsignorecase(“image”)) {

return “blod”;

} else {

return “long”;

}

}

/**

* 驼峰转换

*/

private static string columntoproperty(string column) {

stringbuilder result = new stringbuilder();

// 快速检查

if (column == null || column.isempty()) {

// 没必要转换

return “”;}

else column =column.tolowercase();

if (!column.contains(“_”)) {

// 不含下划线,仅将首字母小写

return column.substring(0, 1).tolowercase() + column.substring(1);

} else {

// 用下划线将原始字符串分割

string[] columns = column.split(“_”);

for (string columnsplit : columns) {

// 跳过原始字符串中开头、结尾的下换线或双重下划线

if (columnsplit.isempty()) {

continue;

}

// 处理真正的驼峰片段

if (result.length() == 0) {

// 第一个驼峰片段,全部字母都小写

result.append(columnsplit.tolowercase());

} else {

// 其他的驼峰片段,首字母大写

result.append(columnsplit.substring(0, 1).touppercase()).append(columnsplit.substring(1).tolowercase());

}

}

return result.tostring();

}

}

/**

* 实体名称转换

*/

private static string formatbeanname(string column) {

stringbuilder result = new stringbuilder();

// 快速检查

if (column == null || column.isempty()) {

// 没必要转换

return “”;

} else if (!column.contains(“_”)) {

// 不含下划线,仅将首字母大写

return column.substring(0, 1).touppercase() + column.substring(1);

} else {

// 用下划线将原始字符串分割

string[] columns = column.split(“_”);

for (string columnsplit : columns) {

// 跳过原始字符串中开头、结尾的下换线或双重下划线

if (columnsplit.isempty()) {

continue;

}

// 处理真正的驼峰片段

result.append(columnsplit.substring(0, 1).touppercase()).append(columnsplit.substring(1).tolowercase());

}

return result.tostring();

}

}

/**

* 实体类字段

*/

private static void getbean(string tablename,string aliasname) {

getconnection = getconnections();

stringbuilder sb = new stringbuilder();

try {

databasemetadata dbmd = getconnection.getmetadata();

resultset rs = dbmd.getcolumns(null, “%”, tablename, “%”);

string beanname = formatbeanname(aliasname);

sb.append(“package “+packagename+”.entity;\n\n”);

sb.append(“import com.baomidou.mybatisplus.annotation.tablename;\n”);

sb.append(“import lombok.data;\n”);

int length=sb.length();

boolean dateflag=false;

sb.append( ” /**\n” +

” * @author ” + author + “\n” +

” * @date “+ format.format(new date())+”\n” +

” */\n” +

“@data\n” +

“@tablename(\””+tablename+”\”)\n” +

“public class “+beanname+”entity {\n”);

while (rs.next()) {

if(formattype(rs.getstring(“type_name”)).equals(“date”)){

dateflag=true;

}

sb.append(“\t//”).append(rs.getstring(“remarks”)).append(defaultvalue(rs.getstring(“column_def”))).append(“\n”);

sb.append(“\tprivate “).append(formattype(rs.getstring(“type_name”))).append(” “).append(columntoproperty(rs.getstring(“column_name”))).append(“;\n”);

}

sb.append(“} “);

if(dateflag){

sb.insert(length, “import java.util.date;\n”);

}

} catch (exception e) {

e.printstacktrace();

}

write(sb.tostring(),”entity.java”,”entity”);

system.err.println(“\n类型:java数据层实体类(bean.java)” + “\n状态:成功” + “\n时间:” + format.format(new date()) + “\n”);

}

/**

* 生成dao层接口

*/

private static void getmapper(string tablename,string aliasname) {

stringbuilder sb = new stringbuilder();

try {

string beanname = formatbeanname(aliasname);

sb.append(“package “+packagename+”.mapper;\n\n”);

sb.append(“import com.baomidou.mybatisplus.core.mapper.basemapper;\n”);

sb.append(“import “+packagename+”.entity.”+beanname+”entity;\n”);

sb.append( “/**\n” +

” * @author ” + author + “\n” +

” * @date “+ format.format(new date())+”\n” +

” */\n” +

“public interface “+beanname+”mapper extends basemapper<“+beanname+”entity>{\n” +

” \n” +

“}”);

} catch (exception e) {

e.printstacktrace();

}

write(sb.tostring(),”mapper.java”,”mapper”);

system.err.println(“\n类型:java数据持久层接口(dao.java)” + “\n状态:成功” + “\n时间:” + format.format(new date()) + “\n”);

}

/**

* 生成service层接口

*/

private static void getservice(string tablename,string aliasname) {

stringbuilder sb = new stringbuilder();

try {

string beanname = formatbeanname(aliasname);

sb.append(“package “+packagename+”.service;\n\n”);

sb.append(“import com.baomidou.mybatisplus.extension.service.impl.serviceimpl;\n”);

sb.append(“import org.springframework.stereotype.service;\n”);

sb.append(“import “+packagename+”.mapper.”+beanname+”mapper;\n”);

sb.append(“import “+packagename+”.entity.”+beanname+”entity;\n”);

sb.append( “/**\n” +

” * @author ” + author + “\n” +

” * @date “+ format.format(new date())+”\n” +

” */\n” +

“@service\n” +

“public class “+beanname+”service extends serviceimpl<“+beanname+”mapper, “+beanname+”entity>{\n” +

“\n” +

“}”);

} catch (exception e) {

e.printstacktrace();

}

write(sb.tostring(),”service.java”,”service”);

system.err.println(“\n类型:java业务层接口(service.java)” + “\n状态:成功” + “\n时间:” + format.format(new date()) + “\n”);

}

/**

* 写文件,支持中文字符,在linux redhad下测试过

* @param str 文本内容

* @param name 文本名称

* */

private static void write(string str, string name,string type) {

try {

file dir = new file(rootpathname +packagepath+ “/” + type);

dir.mkdirs();

string path = dir.getpath() + “/” + formatbeanname(aliasname)+name;

file file = new file(path);

if (!file.exists())

file.createnewfile();

fileoutputstream out = new fileoutputstream(file, false); //如果追加方式用true

stringbuilder sb = new stringbuilder();

sb.append(str + “\n”);

out.write(sb.tostring().getbytes(“utf-8”));//注意需要转换对应的字符集

out.close();

} catch (exception e) {

e.printstacktrace();

}

}

//一次生产所有表

private static void tablenames() {

getconnection = getconnections();

try {

databasemetadata dbmd = getconnection.getmetadata();

resultset rs = dbmd.gettables(getconnection.getcatalog(), null, null, new string[] { “table” });

while (rs.next()) {

tablename=rs.getstring(“table_name”);

aliasname=getaliasname(tablename,”of_”);

//实体

getbean(tablename,aliasname);

//dao层接口

getmapper(tablename,aliasname);

//业务类接口

getservice(tablename,aliasname);

}

} catch (exception e) {

e.printstacktrace();

}

}

public static void main(string[] args) {

// tablenames();

//实体

getbean(tablename,aliasname);

//mapper接口

getmapper(tablename,aliasname);

//业务类接口

getservice(tablename,aliasname);

}

}

生成文件截图

实体

mapper

service