myBatis+Spring+SpringMVC这种框架格式即可使用。当然SpringBoot也是可以的,亲测有效,主要根据MySQL数据库还有表字段,自动生成常用CRUD代码,用了之后才知道有多赞:)
使用之前先定好基础BaseDao<T extends BaseEntity>和接口IBaseService<T extends BaseEntity>,代码即可按照既定好的方法生成。
代码片段以SpringBoot框架为基础;
BaseDao<T extends BaseEntity>:
package com.test.base.dao; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.test.base.entity.BaseEntity; import com.test.base.page.PageInfo; import com.test.base.page.Pager; public abstract class BaseDao<T extends BaseEntity> { @Autowired @Qualifier("readSqlSession") protected SqlSessionTemplate readSqlSession; @Autowired @Qualifier("writeSqlSession") protected SqlSessionTemplate writeSqlSession; private String className; private String directPackageName; private Class<T> cls; /** * 实例化过程中根据泛型获取必要参数,从而对应命名空间 */ @SuppressWarnings("unchecked") public BaseDao() { Type entity = getClass().getGenericSuperclass(); if (ParameterizedType.class.isAssignableFrom(entity.getClass())) { this.cls = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); this.className = this.cls.getSimpleName(); String fullPackageName = this.cls.getPackage().getName(); if(fullPackageName.lastIndexOf(".")==-1){ this.directPackageName = fullPackageName; }else{ this.directPackageName = fullPackageName.substring(fullPackageName.lastIndexOf(".")+1); } } } /** * 指向读取数据 * @return */ public String getReadSql(){ return "read."+this.directPackageName+"."+this.className.toLowerCase()+"."; }; /** * 指向修改数据 * @return */ public String getWriteSql(){ return "write."+this.directPackageName+"."+this.className.toLowerCase()+"."; }; /** * 不得不说,这也是一个设计失误,实际上根本不需要整出一个对面传递进去,好多代码已经沿用就不再修改了 * @param entity * @return */ public T queryById(String id){ Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put("id", id); return readSqlSession.selectOne(getReadSql()+"queryById",paramMap); } /** * 只是一个简单的查询而已,所以无需限制参数类型,这是和分页查询比较明显的区别的地方 * @param entity * @return */ public T selectOne(Object entity){ return readSqlSession.selectOne(getReadSql()+"selectOne",entity); } /** * 只是一个简单的查询而已,所以无需限制参数类型,这是和分页查询比较明显的区别的地方 * @param entity * @param mapId,自定义修改,如果只是简单的修改查询语句,可以使用该方法,原则上不建议修改通用语句 * @return */ public T selectOne(Object entity,String mapId){ return readSqlSession.selectOne(getReadSql()+"selectOne"+mapId,entity); } /** * 这里的参数类型只所以设置为BaseEntity,实际上是因为分页参数的需要,如果只是查询使用,则不必要限制类型 * @param entity * @return */ public int queryByCount(BaseEntity entity){ return readSqlSession.selectOne(getReadSql()+"queryByCount",entity); } /** * 这里的参数类型只所以设置为BaseEntity,实际上是因为分页参数的需要,如果只是查询使用,则不必要限制类型 * @param entity * @param mapId,自定义修改,如果只是简单的修改查询语句,可以使用该方法,原则上不建议修改通用语句 * @return */ public int queryByCount(BaseEntity entity,String mapId){ return readSqlSession.selectOne(getReadSql()+"queryByCount"+mapId,entity); } /** * 只是一个简单的查询而已,所以无需限制参数类型,这是和分页查询比较明显的区别的地方 * @param entity * @return */ public List<T> selectList(Object entity) { return readSqlSession.selectList(getReadSql()+"selectList",entity); } /** * 只是一个简单的查询而已,所以无需限制参数类型,这是和分页查询比较明显的区别的地方 * @param entity * @param mapId,自定义修改,如果只是简单的修改查询语句,可以使用该方法,原则上不建议修改通用语句 * @return */ public List<T> selectList(Object entity,String mapId) { return readSqlSession.selectList(getReadSql()+"selectList"+mapId,entity); } /** * 这里的参数类型只所以设置为BaseEntity,实际上是因为分页参数的需要,如果只是查询使用,则不必要限制类型 * @param entity * @return */ public PageInfo<T> queryByList(BaseEntity entity) { Integer rowCount = queryByCount(entity); Pager pager = entity.getPager(); pager.setRowCount(rowCount); List<T> dataList = readSqlSession.selectList(getReadSql()+"queryByList",entity); return new PageInfo<T>(dataList,pager); } /** * 这里的参数类型只所以设置为BaseEntity,实际上是因为分页参数的需要,如果只是查询使用,则不必要限制类型 * @param entity * @param mapId,自定义修改,如果只是简单的修改查询语句,可以使用该方法,原则上不建议修改通用语句 * @return */ public PageInfo<T> queryByList(BaseEntity entity,String mapId) { Integer rowCount = queryByCount(entity,mapId); Pager pager = entity.getPager(); pager.setRowCount(rowCount); List<T> dataList = readSqlSession.selectList(getReadSql()+"queryByList"+mapId,entity); return new PageInfo<T>(dataList,pager); } /** * 自定义查询集合 * @param entity * @param customMethod * @return */ public <E,F> List<E> selectListCustom(F entity,String customMethod){ return readSqlSession.selectList(getReadSql()+customMethod.trim(), entity); } /** * 自定义查询单体 * @param entity * @param customMethod * @return */ @SuppressWarnings("unchecked") public <E,F> E selectOneCustom(F entity,String customMethod){ return (E) readSqlSession.selectOne(getReadSql()+customMethod.trim(),entity); } /** * 插入对象 * @param object */ public void add(T object) { writeSqlSession.insert(getWriteSql()+"add",object); } /** * 修改数据,修改实体类中不为null的字段数据,用于避免0倍识别为空字符串 * @param object */ public void update(T object) { writeSqlSession.update(getWriteSql()+"update",object); } /** * 修改数据,只修改实体类中不为空的字段数据 * @param object */ public void updateBySelective(T object) { writeSqlSession.update(getWriteSql()+"updateBySelective",object); } /** * 根据ID彻底删除数据,不得不说,这也是一个设计失误,实际上根本不需要整出一个对面传递进去,好多代码已经沿用就不再修改了 * @param id */ public void deleteById(String id){ Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put("id", id); writeSqlSession.delete(getWriteSql()+"deleteById",paramMap); } /** * 根据条件彻底删除数据 * @param entity */ public void deleteBySelective(Object entity){ writeSqlSession.delete(getWriteSql()+"deleteBySelective",entity); } /** * 根据ID逻辑删除数据,不得不说,这也是一个设计失误,实际上根本不需要整出一个对面传递进去,好多代码已经沿用就不再修改了 * @param id */ public void deleteLogicById(String id){ Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put("id", id); writeSqlSession.delete(getWriteSql()+"deleteLogicById",paramMap); } /** * 根据条件逻辑删除数据 * @param entity */ public void deleteLogicBySelective(Object entity){ writeSqlSession.delete(getWriteSql()+"deleteLogicBySelective",entity); } /** * 自定义插入操作 * @param entity * @param customMethod */ public <E> void addEntityCustom(E entity,String customMethod){ writeSqlSession.insert(getWriteSql()+customMethod.trim(),entity); } /** * 自定义更新操作 * @param entity * @param customMethod */ public <E> void updateEntityCustom(E entity,String customMethod){ writeSqlSession.update(getWriteSql()+customMethod.trim(),entity); } /** * 自定义删除操作 * @param entity * @param customMethod */ public <E> void deleteEntityCustom(E entity,String customMethod){ writeSqlSession.delete(getWriteSql()+customMethod.trim(),entity); } }
IBaseService<T extends BaseEntity>:
package com.test.inters.base; import java.util.List; import com.test.base.entity.BaseEntity; import com.test.base.page.PageInfo; /** * Created by Administrator on 2017/3/20. */ public interface IBaseService<T extends BaseEntity> { public T queryById(String id); public T selectOne(Object entity); public int queryByCount(BaseEntity entity); public List<T> selectList(Object entity); public PageInfo<T> queryByList(BaseEntity entity); public void add(T t) throws Exception; public void update(T t) throws Exception; public void updateBySelective(T t) throws Exception; public void deleteById(String... ids) throws Exception; public void deleteBySelective(Object entity) throws Exception; public void deleteLogicById(String... ids) throws Exception; public void deleteLogicBySelective(Object entity) throws Exception; }
生成代码的工具类,主要原理为读取数据库表字段,按照表生成相关Entity,Service,Dao,Mapper
package com.test.core; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dom4j.io.XMLWriter; /** * 自动生成表的实体类 需要修改 packagePath 实体类包名 authorName 作成者姓名 tablename 表名 category * 实体类名(自动首字母大写) 改好后在控制台运行即可,看到success后,右键刷新实体类目录,即可看到,增加serialVersionUID后即可使用 */ public class MysqlUtil { // 数据库连接 private static final String URL = "jdbc:mysql://127.0.0.1:3306/db_test"; private static final String NAME = "root"; private static final String PASS = "root"; private static final String DRIVER = "com.mysql.jdbc.Driver"; // 基本参数设置 private String authorName = "zhangjy";// 作者名字 private String dbname = "configure";// 表名 private String tablename = "tb_app_version";// 表名 private String basePath = "com.test";// 指定实体生成所在包的路径 private boolean is_modify = false;// 是否修改操作(当为true时开启修改模式,如果为false,则is_add,prevFieldName,modifyFieldArr三个值被忽略) private boolean is_add = false;// 添加字段还是删除字段(为true时添加modifyFieldArr中指定的字段对应的相关SQL,为true时删除modifyFieldArr中指定的字段对应的相关SQL) private String prevFieldName = "app_version";// 需要添加在哪个字段之后(如果is_add为false,该值被忽略) private String[] modifyFieldArr = { "app_version", "app_type" };// 需要修改的字段数组(当is_add为true时为添加,当is_add为false时为删除) // 一些通用设置(这些字段的默认值一般不用改变,除非表的设计比较特殊) // 是否去除通用字段(如果包含通用字段则为true,否则为false),通用字段是指create_by,create_date,update_by,update_date,remarks,del_flag private boolean is_creater = true; // 表中是否包含id private boolean is_clude_id = true; // 是否使用简短包名(简短包名往往体现出数据表的功能) private boolean is_use_short_package_path = true; // 是否使用简短类名(简短类型不包含简短包名,但是如果某些类为单个词,或者容易和系统类重名,则可以设置为false,即包含简短包名) private boolean is_use_short_entity_name = true; private String shortPackagePath = null;// 简短包名,用于分类,默认表的第二字段小写 private String packagePath = null;// 指定实体生成所在包的路径 private String entityname = null;// 实体类名 private String shortEntityname = null;// 简短类型,排除表明第一第二段后剩余名称 private String[] colnamesOld; // 列名数组 private String[] colnames; // 列名数组 private String[] colTypes; // 列名类型数组 private String[] colRemarks; // 列注释数组 private boolean f_util = false; // 是否需要导入包java.util.* private boolean f_sql = false; // 是否需要导入包java.sql.* private boolean f_bigdecimal = false; // 是否需要导入包java.sql.* private static Pattern linePattern = Pattern.compile("_(\w)"); /* * 构造函数 */ public MysqlUtil() { String tempStr = null; if (tablename.startsWith("tb_")) { tempStr = tablename.substring(3); } else { tempStr = tablename; } packagePath = tempStr.replace("_", "").toLowerCase(); entityname = lineToHump(tempStr); if (is_use_short_package_path) { String tempShorPackagePathtStr = tempStr.substring(0, tempStr.indexOf("_")); shortPackagePath = tempShorPackagePathtStr.toLowerCase(); } else { shortPackagePath = packagePath; } if (is_use_short_entity_name) { String tempShortEntityStr = tempStr.substring(tempStr.indexOf("_") + 1); shortEntityname = lineToHump(tempShortEntityStr); } else { shortEntityname = entityname; } // 创建连接 Connection con; // 查要生成实体类的表 String sql = "select * from " + tablename; PreparedStatement pStemt = null; try { try { Class.forName(DRIVER); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } con = DriverManager.getConnection(URL, NAME, PASS); pStemt = con.prepareStatement(sql); DatabaseMetaData dbmd = con.getMetaData(); ResultSetMetaData rsmd = pStemt.getMetaData(); int size = rsmd.getColumnCount(); // 统计列 if (size > 7 && is_creater) { if (is_clude_id) { colnamesOld = new String[size - 7]; colnames = new String[size - 7]; colTypes = new String[size - 7]; colRemarks = new String[size - 7]; } else { colnamesOld = new String[size - 6]; colnames = new String[size - 6]; colTypes = new String[size - 6]; colRemarks = new String[size - 6]; } } else { if (is_clude_id) { colnamesOld = new String[size - 1]; colnames = new String[size - 1]; colTypes = new String[size - 1]; colRemarks = new String[size - 1]; } else { colnamesOld = new String[size]; colnames = new String[size]; colTypes = new String[size]; colRemarks = new String[size]; } } int j = 0; ResultSet resultSet = dbmd.getTables(null, "%", tablename, new String[] { "TABLE" }); while (resultSet.next()) { String table = resultSet.getString("TABLE_NAME"); if (tablename.equals(table)) { ResultSet rs = con.getMetaData().getColumns(null, "%", tablename.toUpperCase(), "%"); while (rs.next()) { // System.out.println("字段名:"+rs.getString("COLUMN_NAME")+"--字段注释:"+rs.getString("REMARKS")+"--字段数据类型:"+rs.getString("TYPE_NAME")); String name = rs.getString("COLUMN_NAME"); if ("id".equals(name.toLowerCase()) || "create_date".equals(name.toLowerCase()) || "create_by".equals(name.toLowerCase()) || "update_date".equals(name.toLowerCase()) || "update_by".equals(name.toLowerCase()) || "remarks".equals(name.toLowerCase()) || "del_flag".equals(name.toLowerCase())) { continue; } colnamesOld[j] = name; colnames[j] = lineToHump(name); colTypes[j] = rs.getString("TYPE_NAME"); if (colTypes[j].equalsIgnoreCase("datetime")) { f_util = true; } String remarks = rs.getString("REMARKS"); colRemarks[j] = remarks; j++; } } } String content = parse(colnames, colTypes, colRemarks); try { File directory = new File(""); String path = this.getClass().getResource("").getPath(); String dir1 = directory.getAbsolutePath() + "/src/main/java/" + this.basePath.replace(".", "/") + "/" + "business" + "/" + dbname + "/" + this.shortPackagePath; File directory1 = new File(dir1); if (!directory1.exists()) { directory1.mkdirs(); } System.out.println(path); System.out.println("src/?/" + path.substring(path.lastIndexOf("/com/", path.length()))); String outputPath = dir1 + "/" + initcap(shortEntityname) + ".java"; if (!is_modify) { FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); pw.println(content); pw.flush(); pw.close(); createDao(); createIService(); createService(); createMapper(); } else { try { modifyMapper(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("success!"); } catch (IOException e) { e.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } finally { } } /** * 功能:生成实体类主体代码 * * @param colnames * @param colTypes * @param colSizes * @return */ private String parse(String[] colnames, String[] colTypes, String[] colRemarks) { StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(); StringBuffer sb = new StringBuffer(); sb1.append("package " + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "; "); sb1.append(" "); sb.append("import " + this.basePath + ".base.entity.BaseEntity; "); sb.append(" "); // 注释部分 sb.append("/** "); sb.append(" * " + tablename + " 实体类 "); sb.append(" * " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " " + this.authorName + " "); sb.append(" */ "); // 实体部分 sb.append("public class " + initcap(shortEntityname) + " extends BaseEntity { "); sb.append(" "); processAllAttrs(sb);// 属性 processAllMethod(sb);// get set方法 sb.append("}"); // 判断是否导入工具包 if (f_util) { sb2.append("import java.util.Date; "); sb2.append(" "); } if (f_bigdecimal) { sb2.append("import java.math.BigDecimal; "); sb2.append(" "); } if (f_sql) { sb2.append("import java.sql.*; "); sb2.append(" "); } // System.out.println(sb.toString()); return sb1.append(sb2.toString()).append(sb.toString()).toString(); } /** * 功能:生成所有属性 * * @param sb */ private void processAllAttrs(StringBuffer sb) { sb.append(" /** * * * */ "); sb.append(" private static final long serialVersionUID = 1L; "); sb.append(" "); for (int i = 0; i < colnames.length; i++) { sb.append(" /* " + colRemarks[i] + " */ "); sb.append(" private " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + "; "); sb.append(" "); } } /** * 功能:生成所有方法 * * @param sb */ private void processAllMethod(StringBuffer sb) { for (int i = 0; i < colnames.length; i++) { sb.append(" public void set" + initcap(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + "){ "); sb.append(" this." + colnames[i] + "=" + colnames[i] + "; "); sb.append(" } "); sb.append(" "); sb.append(" public " + sqlType2JavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){ "); sb.append(" return " + colnames[i] + "; "); sb.append(" } "); sb.append(" "); } } /** * 功能:将输入字符串的首字母改成大写 * * @param str * @return */ private String initcap(String str) { char[] ch = str.toCharArray(); if (ch[0] >= 'a' && ch[0] <= 'z') { ch[0] = (char) (ch[0] - 32); } return new String(ch); } /** * 功能:下划线转驼峰 * * @param str * @return */ private String lineToHump(String str) { str = str.toLowerCase(); Matcher matcher = linePattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); } matcher.appendTail(sb); return sb.toString(); } /** * 功能:获得列的数据类型 * * @param sqlType * @return */ private String sqlType2JavaType(String sqlType) { sqlType = sqlType.toUpperCase(); if (sqlType.contains("UNSIGNED")) { sqlType = sqlType.replace("UNSIGNED", "").trim(); } if (sqlType.equalsIgnoreCase("bit")) { return "Boolean"; } else if (sqlType.equalsIgnoreCase("tinyint")) { return "Integer"; } else if (sqlType.equalsIgnoreCase("smallint")) { return "Integer"; } else if (sqlType.equalsIgnoreCase("int")) { return "Integer"; } else if (sqlType.equalsIgnoreCase("bigint")) { f_bigdecimal = true; return "BigDecimal"; } else if (sqlType.equalsIgnoreCase("float")) { f_bigdecimal = true; return "BigDecimal"; } else if (sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("double")) { f_bigdecimal = true; return "BigDecimal"; } else if (sqlType.equalsIgnoreCase("decimal")) { f_bigdecimal = true; return "BigDecimal"; } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("text") || sqlType.equalsIgnoreCase("longtext")) { return "String"; } else if (sqlType.equalsIgnoreCase("datetime")) { f_util = true; return "Date"; } else if (sqlType.equalsIgnoreCase("image")) { return "Blod"; } return null; } /** * 功能:生成实体类DAO * * @param colnames * @param colTypes * @param colSizes * @return * @throws IOException */ private void createDao() throws IOException { String daoName = shortEntityname + "Dao"; File directory = new File(""); String dir1 = directory.getAbsolutePath() + "/src/main/java/" + this.basePath.replace(".", "/") + "/" + "dao" + "/" + this.shortPackagePath; File directory1 = new File(dir1); if (!directory1.exists()) { directory1.mkdirs(); } String outputPath = dir1 + "/" + initcap(daoName) + ".java"; FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); StringBuffer sb = new StringBuffer(); sb.append("package " + this.basePath + ".dao." + this.shortPackagePath + "; "); sb.append(" "); sb.append("import org.springframework.stereotype.Repository; "); sb.append(" "); sb.append("import " + this.basePath + ".base.dao.BaseDao; "); sb.append("import " + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "." + initcap(shortEntityname) + "; "); sb.append(" "); // 注释部分 sb.append("/** "); sb.append(" * 请不要在这里写什么方法,因为根本不需要,这里只是起着一个桥梁过渡作用 "); sb.append(" * " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " " + this.authorName + " "); sb.append(" */ "); sb.append("@Repository "); // 实体部分 sb.append("public class " + initcap(daoName) + "<T extends " + initcap(shortEntityname) + "> extends BaseDao<" + initcap(shortEntityname) + "> { "); sb.append(" "); sb.append("}"); pw.println(sb.toString()); pw.flush(); pw.close(); System.out.println("success!"); } /** * 功能:生成实体类Service * * @param colnames * @param colTypes * @param colSizes * @return * @throws IOException */ private void createIService() throws IOException { String serviceName = shortEntityname + "Service"; File directory = new File(""); String dir1 = directory.getAbsolutePath() + "/src/main/java/" + this.basePath.replace(".", "/") + "/" + "inters" + "/" + dbname + "/" + this.shortPackagePath; File directory1 = new File(dir1); if (!directory1.exists()) { directory1.mkdirs(); } String outputPath = dir1 + "/I" + initcap(serviceName) + ".java"; FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); StringBuffer sb = new StringBuffer(); sb.append("package " + this.basePath + ".inters." + dbname + "." + this.shortPackagePath + "; "); sb.append(" "); sb.append("import " + this.basePath + ".business." + dbname + "." + shortPackagePath + "." + initcap(shortEntityname) + "; "); sb.append("import " + this.basePath + ".inters.base.IBaseService; "); sb.append(" "); // 注释部分 sb.append("/** "); sb.append(" * 对外提供的接口,原则上这里只写自定义语句 "); sb.append(" * " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " " + this.authorName + " "); sb.append(" */ "); // 实体部分 sb.append("public interface I" + initcap(serviceName) + "<T extends " + initcap(shortEntityname) + "> extends IBaseService<" + initcap(shortEntityname) + "> { "); sb.append(" "); sb.append("}"); pw.println(sb.toString()); pw.flush(); pw.close(); System.out.println("success!"); } /** * 功能:生成实体类Service * * @param colnames * @param colTypes * @param colSizes * @return * @throws IOException */ private void createService() throws IOException { String serviceName = shortEntityname + "Service"; String daoName = shortEntityname + "Dao"; File directory = new File(""); String dir1 = directory.getAbsolutePath() + "/src/main/java/" + this.basePath.replace(".", "/") + "/" + "service" + "/" + this.shortPackagePath; File directory1 = new File(dir1); if (!directory1.exists()) { directory1.mkdirs(); } String outputPath = dir1 + "/" + initcap(serviceName) + ".java"; FileWriter fw = new FileWriter(outputPath); PrintWriter pw = new PrintWriter(fw); StringBuffer sb = new StringBuffer(); sb.append("package " + this.basePath + ".service." + this.shortPackagePath + "; "); sb.append(" "); sb.append("import org.springframework.beans.factory.annotation.Autowired; "); sb.append("import org.springframework.stereotype.Service; "); sb.append(" "); sb.append("import " + this.basePath + ".base.service.BaseService; "); sb.append("import " + this.basePath + ".dao." + shortPackagePath + "." + initcap(daoName) + "; "); sb.append("import " + this.basePath + ".business." + dbname + "." + shortPackagePath + "." + initcap(shortEntityname) + "; "); sb.append("import " + this.basePath + ".inters." + dbname + "." + shortPackagePath + ".I" + initcap(serviceName) + "; "); sb.append(" "); // 注释部分 sb.append("/** "); sb.append(" * 对外提供接口的实现,原则上这里只写自定义语句 "); sb.append(" * " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " " + this.authorName + " "); sb.append(" */ "); // 实体部分 sb.append("@Service(value = "" + serviceName + "") "); sb.append("public class " + initcap(serviceName) + "<T extends " + initcap(shortEntityname) + "> extends BaseService<" + initcap(shortEntityname) + "> implements I" + initcap(serviceName) + "<T> { "); sb.append(" "); sb.append(" @Autowired "); sb.append(" private " + initcap(daoName) + "<T> " + daoName + "; "); sb.append(" "); sb.append(" @Override "); sb.append(" public " + initcap(daoName) + "<T> getDao() { "); sb.append(" return this." + daoName + "; "); sb.append(" } "); sb.append("}"); pw.println(sb.toString()); pw.flush(); pw.close(); System.out.println("success!"); } private void createMapper() throws IOException { String mapperName = shortEntityname + "Mapper"; String[] totalColNames = new String[colnames.length + 7]; totalColNames[0] = "id"; for (int i = 0; i < colnamesOld.length; i++) { totalColNames[i + 1] = colnamesOld[i]; } if (is_creater) { totalColNames[colnamesOld.length + 1] = "create_date"; totalColNames[colnamesOld.length + 2] = "create_by"; totalColNames[colnamesOld.length + 3] = "update_date"; totalColNames[colnamesOld.length + 4] = "update_by"; totalColNames[colnamesOld.length + 5] = "remarks"; totalColNames[colnamesOld.length + 6] = "del_flag"; } File directory = new File(""); String dir1 = directory.getAbsolutePath() + "/src/main/resources/" + "maps" + "/" + "read/" + shortPackagePath; File directory1 = new File(dir1); if (!directory1.exists()) { directory1.mkdirs(); } String outputPath = dir1 + "/" + initcap(mapperName) + ".xml"; FileWriter fw = new FileWriter(outputPath); XMLWriter xmlWriter = new XMLWriter(fw); xmlWriter.setEscapeText(false); StringBuffer sb = new StringBuffer(); sb.append("<?xml version="1.0" encoding="UTF-8"?> "); sb.append("<!DOCTYPE mapper "); sb.append(" PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "); sb.append(" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "); sb.append( "<mapper namespace="read." + this.shortPackagePath + "." + shortEntityname.toLowerCase() + ""> "); sb.append(" "); sb.append(" <resultMap id="BaseResultMap" type="" + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "." + initcap(shortEntityname) + "" > "); for (int i = 0; i < totalColNames.length; i++) { if (i == 0) { sb.append(" <id column="" + totalColNames[i] + "" property="" + lineToHump(totalColNames[i]) + ""/> "); } else { sb.append(" <result column="" + totalColNames[i] + "" property="" + lineToHump(totalColNames[i]) + ""/> "); } } sb.append(" </resultMap> "); sb.append(" "); sb.append(" <!-- 配合resultMap使用查询数据列 --> "); sb.append(" <sql id="Base_Result_Map_Column_List"> "); for (int i = 0; i < totalColNames.length; i++) { sb.append(" t." + totalColNames[i]); if (i == totalColNames.length - 1) { sb.append(" "); } else { sb.append(", "); } } sb.append(" </sql> "); sb.append(" "); sb.append(" <!-- 查询数据列 --> "); sb.append(" <sql id="Base_Column_List"> "); for (int i = 0; i < totalColNames.length; i++) { sb.append(" t." + totalColNames[i]); if (!totalColNames[i].equals(lineToHump(totalColNames[i]))) { sb.append(" AS " + lineToHump(totalColNames[i])); } if (i == totalColNames.length - 1) { sb.append(" "); } else { sb.append(", "); } } sb.append(" </sql> "); sb.append(" "); sb.append(" <!-- 查询条件 --> "); sb.append(" <sql id="Where_Clause"> "); sb.append(" where 1=1 "); sb.append(" <trim suffixOverrides=","> "); for (int i = 0; i < totalColNames.length; i++) { sb.append(" <if test="" + lineToHump(totalColNames[i]) + " != null and " + lineToHump(totalColNames[i]) + " != ''" > "); sb.append(" and t." + totalColNames[i]); sb.append("=#{"); sb.append(lineToHump(totalColNames[i])); sb.append("}"); sb.append(" "); sb.append(" </if> "); } sb.append(" </trim> "); sb.append(" </sql> "); sb.append(" "); sb.append(" <!-- 根据id查询 --> "); sb.append(" <select id="queryById" resultType="" + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "." + initcap(shortEntityname) + "" parameterType="Object"> "); sb.append(" select "); sb.append(" <include refid="Base_Column_List" /> "); sb.append(" from " + tablename + " t "); sb.append(" where t.id = #{id} "); sb.append(" </select> "); sb.append(" "); sb.append(" <!-- 查询 --> "); sb.append(" <select id="selectOne" resultType="" + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "." + initcap(shortEntityname) + "" parameterType="Object"> "); sb.append(" select "); sb.append(" <include refid="Base_Column_List" /> "); sb.append(" from " + tablename + " t "); sb.append(" <include refid="Where_Clause" /> "); sb.append(" </select> "); sb.append(" "); sb.append(" <!-- 查询集合 --> "); sb.append(" <select id="selectList" resultType="" + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "." + initcap(shortEntityname) + "" parameterType="Object"> "); sb.append(" select "); sb.append(" <include refid="Base_Column_List" /> "); sb.append(" from " + tablename + " t "); sb.append(" <include refid="Where_Clause" /> "); sb.append(" </select> "); sb.append(" "); sb.append(" <!-- 查询总数 --> "); sb.append(" <select id="queryByCount" resultType="java.lang.Integer" parameterType="Object"> "); sb.append(" select count(1) from " + tablename + " t "); sb.append(" <include refid="Where_Clause" /> "); sb.append(" </select> "); sb.append(" "); sb.append(" <!-- 查询列表--> "); sb.append(" <select id="queryByList" resultType="" + this.basePath + ".business." + dbname + "." + this.shortPackagePath + "." + initcap(shortEntityname) + "" parameterType="Object"> "); sb.append(" select "); sb.append(" <include refid="Base_Column_List" /> "); sb.append(" from " + tablename + " t "); sb.append(" <include refid="Where_Clause" /> "); sb.append(" <if test="pager.orderCondition != null and pager.orderCondition != ''"> "); sb.append(" ${pager.orderCondition} "); sb.append(" </if> "); sb.append(" <if test="pager.mysqlQueryCondition != null and pager.mysqlQueryCondition != ''"> "); sb.append(" ${pager.mysqlQueryCondition} "); sb.append(" </if> "); sb.append(" </select> "); sb.append(" "); sb.append("</mapper>"); xmlWriter.write(sb.toString()); xmlWriter.flush(); xmlWriter.close(); String dir2 = directory.getAbsolutePath() + "/src/main/resources/" + "maps" + "/" + "write/" + shortPackagePath; File directory2 = new File(dir2); if (!directory2.exists()) { directory2.mkdirs(); } String outputPath2 = dir2 + "/" + initcap(mapperName) + ".xml"; FileWriter fw2 = new FileWriter(outputPath2); XMLWriter xmlWriter2 = new XMLWriter(fw2); xmlWriter2.setEscapeText(false); StringBuffer sb2 = new StringBuffer(); sb2.append("<?xml version="1.0" encoding="UTF-8"?> "); sb2.append("<!DOCTYPE mapper "); sb2.append(" PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "); sb2.append(" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "); sb2.append( "<mapper namespace="write." + this.shortPackagePath + "." + shortEntityname.toLowerCase() + ""> "); sb2.append(" "); sb2.append(" <!-- 查询条件 --> "); sb2.append(" <sql id="Where_Clause"> "); sb2.append(" where 1=1 "); sb2.append(" <trim suffixOverrides=","> "); for (int i = 0; i < totalColNames.length; i++) { sb2.append(" <if test="" + lineToHump(totalColNames[i]) + " != null and " + lineToHump(totalColNames[i]) + " != ''" > "); sb2.append(" and t." + totalColNames[i]); sb2.append("=#{"); sb2.append(lineToHump(totalColNames[i])); sb2.append("}"); sb2.append(" "); sb2.append(" </if> "); } sb2.append(" </trim> "); sb2.append(" </sql> "); sb2.append(" "); sb2.append(" <!-- 插入记录 --> "); sb2.append(" <insert id="add" parameterType="Object"> "); sb2.append(" insert into " + tablename + " ( "); for (int i = 0; i < totalColNames.length; i++) { sb2.append(" " + totalColNames[i]); if (i != totalColNames.length - 1) { sb2.append(", "); } } sb2.append(") "); sb2.append(" values ( "); for (int i = 0; i < totalColNames.length; i++) { sb2.append(" #{"); sb2.append(lineToHump(totalColNames[i])); sb2.append("}"); if (i != totalColNames.length - 1) { sb2.append(", "); } } sb2.append(") "); sb2.append(" </insert> "); sb2.append(" "); sb2.append(" <!-- 修改记录,只修改只不为空的字段 --> "); sb2.append(" <update id="updateBySelective" parameterType="Object" > "); sb2.append(" update " + tablename + " set "); sb2.append(" <trim suffixOverrides="," > "); for (int i = 1; i < totalColNames.length; i++) { sb2.append(" <if test="" + lineToHump(totalColNames[i]) + " != null and " + lineToHump(totalColNames[i]) + " != ''" > "); sb2.append(" " + totalColNames[i]); sb2.append("=#{"); sb2.append(lineToHump(totalColNames[i])); sb2.append("}"); if (i != totalColNames.length - 1) { sb2.append(","); } sb2.append(" "); sb2.append(" </if> "); } sb2.append(" </trim> "); sb2.append(" where id = #{id} "); sb2.append(" </update> "); sb2.append(" "); sb2.append(" <!-- 修改记录,只要不为null都进行修改,避免0位识别为空字符串 --> "); sb2.append(" <update id="update" parameterType="Object" > "); sb2.append(" update " + tablename + " set "); sb2.append(" <trim suffixOverrides="," > "); for (int i = 1; i < totalColNames.length; i++) { sb2.append(" <if test="" + lineToHump(totalColNames[i]) + " != null" > "); sb2.append(" " + totalColNames[i]); sb2.append("=#{"); sb2.append(lineToHump(totalColNames[i])); sb2.append("}"); if (i != totalColNames.length - 1) { sb2.append(","); } sb2.append(" "); sb2.append(" </if> "); } sb2.append(" </trim> "); sb2.append(" where id = #{id} "); sb2.append(" </update> "); sb2.append(" "); sb2.append(" <!-- 按照条件删除记录,彻底删除 --> "); sb2.append(" <delete id="deleteBySelective" parameterType="Object" > "); sb2.append(" delete t from " + tablename + " t "); sb2.append(" <include refid="Where_Clause" /> "); sb2.append(" </delete> "); sb2.append(" "); sb2.append(" <!-- 按照ID删除记录,彻底删除 --> "); sb2.append(" <delete id="deleteById" parameterType="Object" > "); sb2.append(" delete from " + tablename + " "); sb2.append(" where id = #{id} "); sb2.append(" </delete> "); sb2.append(" "); sb2.append(" <!-- 按照条件删除记录,逻辑删除 --> "); sb2.append(" <update id="deleteLogicBySelective" parameterType="Object"> "); sb2.append(" update " + tablename + " t set t.del_flag=1 "); sb2.append(" <include refid="Where_Clause" /> "); sb2.append(" </update> "); sb2.append(" "); sb2.append(" <!-- 按照ID删除记录,逻辑删除 --> "); sb2.append(" <update id="deleteLogicById" parameterType="Object"> "); sb2.append(" update " + tablename + " set del_flag=1 "); sb2.append(" where id = #{id} "); sb2.append(" </update> "); sb2.append(" "); sb2.append("</mapper>"); xmlWriter2.write(sb2.toString()); xmlWriter2.flush(); xmlWriter2.close(); } private void modifyMapper() throws Exception { int readCnt = 0; int writeCnt = 0; String mapperName = shortEntityname + "Mapper"; File directory = new File(""); String dir1 = directory.getAbsolutePath() + "/src/main/resources/" + "maps" + "/" + "read/" + shortPackagePath; File directory1 = new File(dir1); if (!directory1.exists()) { directory1.mkdirs(); } StringBuffer tempSb1 = new StringBuffer(); String outputPath1 = dir1 + "/" + initcap(mapperName) + ".xml"; RandomAccessFile raf1 = new RandomAccessFile(outputPath1, "r"); String currReadLineString = null; while (raf1.getFilePointer() < raf1.length()) { currReadLineString = new String(raf1.readLine().getBytes("ISO-8859-1"), "utf-8"); if (is_add) { if (readCnt <= 3) { tempSb1.append(currReadLineString + " "); if (currReadLineString.equals(" <result column="" + prevFieldName + "" property="" + lineToHump(prevFieldName) + ""/>")) { readCnt++; for (String tempStr : modifyFieldArr) { tempSb1.append(" <result column="" + tempStr + "" property="" + lineToHump(tempStr) + ""/> "); } } else if (currReadLineString.equals(" t." + prevFieldName + ",")) { readCnt++; for (String tempStr : modifyFieldArr) { tempSb1.append(" t." + tempStr + ", "); } } else if (currReadLineString .equals(" t." + prevFieldName + " AS " + lineToHump(prevFieldName) + ",")) { readCnt++; for (String tempStr : modifyFieldArr) { tempSb1.append(" t." + tempStr + " AS " + lineToHump(tempStr) + ", "); } } else if (currReadLineString.equals(" <if test="" + lineToHump(prevFieldName) + " != null and " + lineToHump(prevFieldName) + " != ''" > ")) { readCnt++; currReadLineString = new String(raf1.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb1.append(currReadLineString + " "); currReadLineString = new String(raf1.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb1.append(currReadLineString + " "); for (String tempStr : modifyFieldArr) { tempSb1.append(" <if test="" + lineToHump(tempStr) + " != null and " + lineToHump(tempStr) + " != ''" > ") .append(" and t." + tempStr + "=#{" + lineToHump(tempStr) + "} ") .append(" </if> "); } } } else { tempSb1.append(currReadLineString + " "); } } else { if (readCnt <= modifyFieldArr.length * 4 - 1) { boolean is_del = false; for (String tempStr : modifyFieldArr) { if (currReadLineString .equals(" <result column="" + tempStr + "" property="" + lineToHump(tempStr) + ""/>") || currReadLineString.equals(" t." + tempStr + ",") || currReadLineString.equals(" t." + tempStr + " AS " + lineToHump(tempStr) + ",")) { readCnt++; is_del = true; } if (currReadLineString.equals(" <if test="" + lineToHump(tempStr) + " != null and " + lineToHump(tempStr) + " != ''" > ")) { readCnt++; raf1.readLine(); raf1.readLine(); is_del = true; } } if (!is_del) { tempSb1.append(currReadLineString + " "); } } else { tempSb1.append(currReadLineString + " "); } } } raf1.close(); FileWriter fw1 = new FileWriter(outputPath1); XMLWriter xmlWriter1 = new XMLWriter(fw1); xmlWriter1.setEscapeText(false); xmlWriter1.write(tempSb1.toString()); xmlWriter1.flush(); xmlWriter1.close(); String dir2 = directory.getAbsolutePath() + "/src/main/resources/" + "maps" + "/" + "write/" + shortPackagePath; File directory2 = new File(dir2); if (!directory2.exists()) { directory2.mkdirs(); } StringBuffer tempSb2 = new StringBuffer(); String outputPath2 = dir2 + "/" + initcap(mapperName) + ".xml"; RandomAccessFile raf2 = new RandomAccessFile(outputPath2, "r"); while (raf2.getFilePointer() < raf2.length()) { currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); if (is_add) { if (writeCnt <= 4) { tempSb2.append(currReadLineString + " "); if (currReadLineString.equals(" <if test="" + lineToHump(prevFieldName) + " != null and " + lineToHump(prevFieldName) + " != ''" > ")) { writeCnt++; if (writeCnt % 5 == 1) { currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb2.append(currReadLineString + " "); currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb2.append(currReadLineString + " "); for (String tempStr : modifyFieldArr) { tempSb2.append(" <if test="" + lineToHump(tempStr) + " != null and " + lineToHump(tempStr) + " != ''" > ") .append(" and t." + tempStr + "=#{" + lineToHump(tempStr) + "} ") .append(" </if> "); } } if (writeCnt % 5 == 4) { currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb2.append(currReadLineString + " "); currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb2.append(currReadLineString + " "); for (String tempStr : modifyFieldArr) { tempSb2.append(" <if test="" + lineToHump(tempStr) + " != null and " + lineToHump(tempStr) + " != ''" > ") .append(" " + tempStr + "=#{" + lineToHump(tempStr) + "}, ") .append(" </if> "); } } } else if (currReadLineString.equals(" " + prevFieldName + ",")) { writeCnt++; for (String tempStr : modifyFieldArr) { tempSb2.append(" " + tempStr + ", "); } } else if (currReadLineString.equals(" #{" + lineToHump(prevFieldName) + "},")) { writeCnt++; for (String tempStr : modifyFieldArr) { tempSb2.append(" #{" + lineToHump(tempStr) + "}, "); } } else if (currReadLineString .equals(" <if test="" + lineToHump(prevFieldName) + " != null" > ")) { writeCnt++; currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb2.append(currReadLineString + " "); currReadLineString = new String(raf2.readLine().getBytes("ISO-8859-1"), "utf-8"); tempSb2.append(currReadLineString + " "); for (String tempStr : modifyFieldArr) { tempSb2.append(" <if test="" + lineToHump(tempStr) + " != null" > ") .append(" " + tempStr + "=#{" + lineToHump(tempStr) + "}, ") .append(" </if> "); } } } else { tempSb2.append(currReadLineString + " "); } } else { if (writeCnt <= modifyFieldArr.length * 5 - 1) { boolean is_del = false; for (String tempStr : modifyFieldArr) { if (currReadLineString.equals(" " + tempStr + ",") || currReadLineString.equals(" #{" + lineToHump(tempStr) + "},")) { writeCnt++; is_del = true; } if (currReadLineString .equals(" <if test="" + lineToHump(tempStr) + " != null and " + lineToHump(tempStr) + " != ''" > ") || currReadLineString .equals(" <if test="" + lineToHump(tempStr) + " != null" > ")) { writeCnt++; raf2.readLine(); raf2.readLine(); is_del = true; } } if (!is_del) { tempSb2.append(currReadLineString + " "); } } else { tempSb2.append(currReadLineString + " "); } } } raf2.close(); FileWriter fw2 = new FileWriter(outputPath2); XMLWriter xmlWriter2 = new XMLWriter(fw2); xmlWriter2.setEscapeText(false); xmlWriter2.write(tempSb2.toString()); xmlWriter2.flush(); xmlWriter2.close(); } /** * 出口 TODO * * @param args */ public static void main(String[] args) { new MysqlUtil(); } }