一共是四层,为dao+service+mapper+model,控制器因为不需要逐表生成,因而省略。
package create;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Create
{
static final String tablename = "edu_goods";
static final String packagePath = "/src/main/java/com/test";
static final String pakageName = "test";
private static String PATH;
private static Map dbInfo;
private static String PK;
private Map<String,String> propertylist;
private Map<String,String> columnComments;
/**
* 初始化配置信息
*/
static
{
try {
//读取根路径
File file = new File("");
PATH = file.getAbsolutePath();
// //简历项目文件夹
// File f = new File(PATH + "/src/main/java/com/test");
// if (!f.exists()) f.mkdir();
// File f1 = new File(PATH + "/src/main/java/com/test/dao");
// if (!f1.exists()) f1.mkdir();
// File f2 = new File(PATH + "/src/main/java/com/test/service");
// if (!f2.exists()) f2.mkdir();
// File f3 = new File(PATH + "/src/main/java/com/test/model");
// if (!f3.exists()) f3.mkdir();
// File f4 = new File(PATH + "/src/main/java/com/test/controller");
// if (!f4.exists()) f4.mkdir();
//设置配置信息
InputStream inputStream = new BufferedInputStream(new FileInputStream(PATH + "/src/main/resources/application.properties"));
Properties properties = new Properties();
properties.load(inputStream);
Map db = new HashMap();
db.put("url",properties.getProperty("spring.datasource.url"));
db.put("username",properties.getProperty("spring.datasource.username"));
db.put("password",properties.getProperty("spring.datasource.password"));
db.put("driverName",properties.getProperty("spring.datasource.driver-class-name"));
dbInfo = db;
inputStream.close();
//设置jdbc反射对象
Class.forName(dbInfo.get("driverName").toString());
} catch (Exception e) {
e.printStackTrace();
}
};
public static void main(String[] args) throws IOException
{
Create create = new Create();
List list = create.get_tablename_list();
for (int i = 0;i < list.size();i++) {
//生成dao
create.createDao(list.get(i).toString());
//生成service
create.createService(list.get(i).toString());
//生成xml
create.createMapperXml(list.get(i).toString());
//生成model
create.createModel(list.get(i).toString());
}
}
/**
* 生成dao
*/
public void createDao(String tablename)
{
tablename = underlineToCamel(tablename);
String content = this.readToString(PATH + "/src/main/resources/example/exampleMapper.temp");
//替换包名
content = content.replaceAll("examplepackage",pakageName);
//替换实例名称
content = content.replaceAll("example",tablename);
//生成文件
String mapperName = PATH + packagePath + "/dao/" + tablename + "Mapper.java";
this.writeContent(mapperName,content);
System.out.println("文件" + mapperName + "创建成功");
}
/**
* 生成service
*/
public void createService(String tablename)
{
tablename = underlineToCamel(tablename);
String content = this.readToString(PATH + "/src/main/resources/example/exampleService.temp");
//替换包名
content = content.replaceAll("examplepackage",pakageName);
//替换实例名称
content = content.replaceAll("example",tablename);
//生成文件
String serviceName = PATH + packagePath + "/service/" + tablename + "Service.java";
this.writeContent(serviceName,content);
System.out.println("文件" + serviceName + "创建成功");
}
/**
* 生成sql查询文件
*/
public void createMapperXml(String tablename)
{
String tableName = underlineToCamel(tablename);
String content = this.readToString(PATH + "/src/main/resources/example/exampleMapperXML.temp");
//替换包名
content = content.replaceAll("examplepackage",pakageName);
//替换实例名称
content = content.replaceAll("example",tableName);
//替换表名和主键
content = content.replaceAll("tablename",tablename)
.replaceAll("PK",this.getPK(tablename));
//替换字段
try {
String fieldlist = "";
Map list = this.getTableInfo(tablename);
Iterator iterator = list.keySet().iterator();
int count = 0;
while (iterator.hasNext()) {
if(count > 0) fieldlist += ",";
fieldlist += iterator.next();
count ++;
}
content = content.replaceAll("(field_list|value_list)",fieldlist);
} catch (Exception e) {
e.printStackTrace();
}
//生成文件
String xmlName = PATH + "/src/main/resources/mapper/" + tableName + "Mapper.xml";
this.writeContent(xmlName,content);
System.out.println("文件" + xmlName + "创建成功");
}
/**
* 生成model
*/
public void createModel(String tablename)
{
String tableName = underlineToCamel(tablename);
String content = this.readToString(PATH + "/src/main/resources/example/exampleModel.temp");
//替换包名
content = content.replaceAll("examplepackage",pakageName);
//替换实例名称
content = content.replaceAll("example",tableName);
//替换表名和主键
content = content.replaceAll("tablename",tablename)
.replaceAll("PK",PK);
//生成属性
content = content.replaceAll("property",this.createModelProperty(tablename));
//生成方法
content = content.replaceAll("method",this.createModelMethod(tablename));
//生成打印方法
content = content.replaceAll("toString_",this.createModeltoString(tablename));
//生成文件
String modelName = PATH + packagePath + "/model/" + tableName + "Model.java";
this.writeContent(modelName,content);
System.out.println("文件" + modelName + "创建成功");
}
/**
* 生成model属性
*/
private String createModelProperty(String tablename)
{
String content = "";
try {
Map<String,String> propertylist = this.getTableInfo(tablename);
this.propertylist = propertylist;
Map<String,String> columnComments = this.getColumnComments(tablename);
this.columnComments = columnComments;
Iterator<String> iterator = propertylist.keySet().iterator();
int count = 0;
while (iterator.hasNext()) {
String next = iterator.next();
if(count > 0) content += "\t";
content += "/** @var " + propertylist.get(next) + " " + columnComments.get(next) + " */\r";
content += "\t@TableField(" + "\""+ next + "\"" + ")\r";
content += "\tprivate " + this.getFieldType(propertylist.get(next)) + " " + next + ";\n";
count ++;
}
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 生成model方法
*/
private String createModelMethod(String tablename)
{
String content = "";
try {
Iterator<String> iterator = propertylist.keySet().iterator();
int count = 0;
while (iterator.hasNext()) {
String next = iterator.next();
if(count > 0) content += "\t";
//生成set方法
content += "/** @var " + propertylist.get(next) + " " + columnComments.get(next) + " */\r";
String returnname = underlineToCamel(tablename) + "Model";
String setname = "set" + underlineToCamel(next)
+ "("
+ this.getFieldType(propertylist.get(next))
+ " "
+ next
+ ")";
content += "\tpublic " + returnname + " " + setname + "\r";
content += "\t{\r";
content += "\t\tthis." + next + " = " + next + ";\r";
content += "\t\treturn this;\r";
content += "\t}\r";
//生成get方法
content += "\t/** @var " + propertylist.get(next) + " " + columnComments.get(next) + " */\r";
String getname = "get" + underlineToCamel(next) + "()";
content += "\tpublic " + this.getFieldType(propertylist.get(next)) + " " + getname + "\r";
content += "\t{\r";
content += "\t\treturn this." + next + ";\r";
content += "\t}\n";
count ++;
}
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 生成model打印方法
*/
public String createModeltoString(String tablename)
{
tablename = underlineToCamel(tablename);
String content = "\"" +tablename+":\" + \n";
try {
List<String> mapKeyList = new ArrayList<String>(propertylist.keySet());
for (int i = 0;i < mapKeyList.size();i++) {
content += "\t\t";
if (i > 0) {
content += "\"," + mapKeyList.get(i) + " = \" + " + mapKeyList.get(i);
} else {
content += "\"" + mapKeyList.get(i) + " = \" + " + mapKeyList.get(i);
}
if (i < mapKeyList.size()-1) content += " + \r";
}
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 读取文件内容
* @param fileName
* @return
*/
public String readToString(String fileName) {
String encoding = "UTF-8";
File file = new File(fileName);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(filecontent, encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
* 生成并写入文件内容
*/
public void writeContent(String writePath,String content)
{
System.out.println(writePath);
File myFilePath = new File(writePath);
try {
if (!myFilePath.exists()) myFilePath.createNewFile();
FileWriter fileWriter = new FileWriter(myFilePath);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println(content);
printWriter.close();
//System.out.println(writePath + "创建成功");
} catch (Exception e) {
System.out.println(writePath + "创建失败");
e.printStackTrace();
}
}
/**
* 获取表名
*/
private <T> List get_tablename_list()
{
List<String> tablelist = new ArrayList<String>();
if (tablename != ""){
tablelist.add(tablename);
} else {
try {
Connection conn = this.getConnection();
DatabaseMetaData databaseMetaData = conn.getMetaData();
//PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = databaseMetaData.getTables(null, null, null,new String[] { "TABLE" });
while (rs.next()) {
tablelist.add(rs.getString(3));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return tablelist;
}
/**
* 获取表字段和字段类型
*/
public Map getTableInfo(String tablename) throws SQLException
{
String sql = "select COLUMN_NAME,DATA_TYPE from information_schema.COLUMNS where table_name = \"{tablename}\"";
sql = sql.replace("{tablename}",tablename);
Map<String,String> info = new HashMap<String,String>();
Connection conn = this.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
info.put(rs.getString("COLUMN_NAME"),rs.getString("DATA_TYPE"));
}
this.closeAll(conn,pstmt,rs);
return info;
}
/**
* 获取表中字段的所有注释
* @param tableName
* @return
*/
public Map<String,String> getColumnComments(String tableName)
{
Map<String,String> columnComments = new HashMap<String,String>();
//与数据库的连接
String tableSql = "show full columns from " + tableName;
try {
Connection conn = this.getConnection();
PreparedStatement pstmt = conn.prepareStatement(tableSql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
columnComments.put(rs.getString("Field"),rs.getString("Comment"));
}
this.closeAll(conn,pstmt,rs);
} catch (SQLException e) {
e.printStackTrace();
}
return columnComments;
}
/**
* 获取某个数据表的主键
*/
public String getPK(String tablename)
{
String key = "";
try {
Connection connection = this.getConnection();
String catalog = connection.getCatalog();//数据库名
DatabaseMetaData dbmd = connection.getMetaData();
ResultSet p_key = dbmd.getPrimaryKeys(catalog,null,tablename);
while (p_key.next()) {
key = p_key.getString("COLUMN_NAME");
}
connection.close();
p_key.close();
} catch (Exception e) {
e.printStackTrace();
}
PK = key;
return key;
}
/**
* 获取model属性类型
*/
private String getFieldType(String type)
{
String newType = "String";
switch (type) {
case "tinyint":newType = "int";break;
case "int":newType = "int";break;
case "decimal":newType = "double";break;
}
return newType;
}
/**
* 下划线格式字符串转换为驼峰格式字符串2
*
* @param param
* @return
*/
public static String underlineToCamel(String param) {
if (param == null || "".equals(param.trim())) {
return "";
}
StringBuilder sb = new StringBuilder(Create.toUpperCaseFirstOne(param));
Matcher mc = Pattern.compile("_").matcher(param);
int i = 0;
while (mc.find()) {
int position = mc.end() - (i++);
sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
}
return sb.toString();
}
//首字母转大写
public static String toUpperCaseFirstOne(String s){
if(Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
/**
* 判断字符串是否为空
*/
public static boolean checkString(String str)
{
if (str != null && !"".equals(str.trim())) {
return true;
}
return false;
}
/**
* 获取数据库连接
* @return
*/
private Connection getConnection()
{
Connection connection = null;
try {
connection = DriverManager.getConnection(dbInfo.get("url").toString(),
dbInfo.get("username").toString(),
dbInfo.get("password").toString()
);
} catch (SQLException se){
se.printStackTrace();
}
return connection;
}
/**
* 关闭mysql数据库连接
*/
private void closeAll(Connection con, Statement stmt, ResultSet rs)
{
try {
if (rs != null){
rs.close();
}
if (stmt != null){
stmt.close();
}
if (rs != null){
rs.close();
}
} catch (SQLException ce) {
ce.printStackTrace();
}
}
}
exampleMapper模板:
package com.examplepackage.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.examplepackage.model.exampleModel;
import java.util.List;
import java.util.Map;
@Repository
@Mapper
public interface exampleMapper extends BaseMapper<exampleModel>
{
List<exampleModel> getList();//获取所有信息
List<exampleModel> getListByMap(@Param("params") Map<String,Object> map);//通过map字典查询
List<exampleModel> getListByArray(@Param("idlist") int[] idlist);//通过主键组合数组查询
Object getField(@Param("field") String field,@Param("params") Map<String,Object> map);//查询单个字段
Page<exampleModel> getListPage(@Param("params") Map<String,Object> map);//分页查询
exampleModel detail(@Param("id") int id);//通过主键获取一行数据
exampleModel detailByMap(@Param("params") Map<String,Object> map);//通过map字典查询一行数据
int addexampleModel(exampleModel example);//增加数据返回生成数据的主键
boolean updateexampleModel(@Param("data") Map<String,Object> map,@Param("where") Map<String,Object> where);//修改数据
boolean deleteexampleModel(@Param("id") int id);//通过主键删除数据
boolean deleteexampleModelByArray(@Param("idlist") int[] idlist);//通过主键删除多行数据
boolean deleteexampleModelByMap(@Param("params") Map<String,Object> map);//通过map字典删除数据
}
exampleMapperXML模板
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.examplepackage.dao.exampleMapper">
<select id="getList" resultType="com.examplepackage.model.exampleModel">
select * from tablename;
</select>
<select id="getListbyMap" parameterType="java.util.Map" resultType="com.examplepackage.model.exampleModel">
select * from tablename where
<foreach collection="params.keys" item="key" open="(" close=")" separator="," >
${key} = #{params[${key}]}
</foreach>
</select>
<select id="getListByArray" parameterType="java.util.Arrays" resultType="com.examplepackage.model.exampleModel">
select * from tablename where PK IN
<foreach collection="idlist" item="item" index="index" open="(" close=")" separator="," >
#{item}
</foreach>
</select>
<select id="getField" resultType="java.lang.Object">
select ${field} from tablename where
<foreach collection="params.keys" item="key" open="(" close=")" separator="," >
${key} = #{params[${key}]}
</foreach>
limit 0,1
</select>
<select id="getListPage" resultType="com.examplepackage.model.exampleModel" parameterType="java.util.Map">
select * from tablename where
<foreach collection="params.keys" item="key" open="(" close=")" separator="," >
${key} = #{params[${key}]}
</foreach>
</select>
<select id="detail" resultType="com.examplepackage.model.exampleModel" parameterType="java.lang.Integer">
select * from tablename where PK = ${id} limit 0,1
</select>
<select id="detailByMap" resultType="com.examplepackage.model.exampleModel" parameterType="java.util.Map">
select * from tablename where
<foreach collection="params.keys" item="key" open="(" close=")" separator="," >
${key} = #{params[${key}]}
</foreach>
</select>
<insert id="addexampleModel" parameterType="com.examplepackage.model.exampleModel" keyProperty="id" useGeneratedKeys="true">
insert into tablename (field_list) values ( value_list )
</insert>
<update id="updateexampleModel" parameterType="java.util.Map">
update tablename set
<foreach collection="data.keys" item="key" open="(" close=")" separator="," >
${key} = #{data[${key}]}
</foreach>
where
<foreach collection="where.keys" item="key" open="(" close=")" separator="," >
${key} = #{where[${key}]}
</foreach>
</update>
<delete id="deleteexampleModel" parameterType = "java.lang.Integer">
delete from tablename where PK = ${id}
</delete>
<delete id="deleteexampleModelByArray" parameterType = "java.util.Arrays">
delete from tablename where PK in
<foreach collection="idlist" item="item" index="index" open="(" close=")" separator="," >
#{item}
</foreach>
</delete>
<delete id="deleteexampleModelByMap" parameterType = "java.util.Map">
delete from tablename where
<foreach collection="params.keys" item="key" open="(" close=")" separator="," >
${key} = #{params[${key}]}
</foreach>
</delete>
</mapper>
exampleService模板
package com.examplepackage.service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.examplepackage.dao.exampleMapper;
import com.examplepackage.model.exampleModel;
import java.util.List;
import java.util.Map;
@Service
public class exampleService
{
@Autowired
private exampleMapper example;
/**
* 查询所有数据
* @return
*/
public List<exampleModel> getList()
{
return example.getList();
}
/**
* 通过字典查询所有数据
* @param where
* @return
*/
public List<exampleModel> getListByMap(Map<String,Object> where)
{
return example.getListByMap(where);
}
/**
* 组合主键数组查询
* @param idlist
* @return
*/
public List<exampleModel> getListByArray(int[] idlist)
{
return example.getListByArray(idlist);
}
/**
* 查询单个字段
* @param field
* @param where
* @return
*/
public Object getField(String field,Map<String,Object> where)
{
return example.getField(field,where);
}
/**
* 分页查询
* @param where
* @param pageNo
* @param pageSize
* @return
*/
public Page<exampleModel> getListPage(Map<String,Object> where,int pageNo, int pageSize)
{
PageHelper.startPage(pageNo,pageSize);
return example.getListPage(where);
}
/**
* 主键查询获取一行数据
* @param id
* @return
*/
public exampleModel detail(int id)
{
return example.detail(id);
}
/**
* map字典查询一行数据
* @param where
* @return
*/
public exampleModel detailByMap(Map<String,Object> where)
{
return example.detailByMap(where);
}
/**
* 添加一行数据
* @param model
* @return
*/
public int addexampleModel(exampleModel model)
{
return example.addexampleModel(model);
}
/**
* 修改数据
* @param data
* @param where
* @return
*/
public boolean updateexampleModel(Map<String,Object> data,Map<String,Object> where)
{
return example.updateexampleModel(data,where);
}
/**
* 通过主键删除多行数据
* @param idlist
* @return
*/
public boolean deleteexampleModelByArray(int[] idlist)
{
return example.deleteexampleModelByArray(idlist);
}
/**
* 通过主键删除一行数据
* @param id
* @return
*/
public boolean deleteexampleModel(int id)
{
return example.deleteexampleModel(id);
}
/**
* 通过map字典删除数据
* @param map
* @return
*/
public boolean deleteexampleModelByMap(Map<String,Object> map)
{
return example.deleteexampleModelByMap(map);
}
}
exampleModel模板
package com.examplepackage.model;
import java.io.Serializable;
import com.baomidou.mybatisplus.enums.IdType;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("tablename")
public class exampleModel extends Model<exampleModel>
{
private static final long serialVersionUID = 1L;
property
method
@Override
protected Serializable pkVal()
{
return this.PK;
}
@Override
public String toString()
{
return toString_;
}
}
生成后的一般的增删改查方法都有了,可以加速开发速度