生活随笔
收集整理的這篇文章主要介紹了
一些记录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼生成器
根據Mybatis generator(MBG)結合freemarker寫了一個代碼生成器,可以直接生成Controller,Service,Dao,bean,以及對應的mapper.xml文件。
準備材料: 幾個模板,mybatis-generator-core-1.3.2.jar。
注意事項:各個公司的文件結構可能不盡相同,所以請根據實際情況自行采用。
public class MapperGeneratorTest {/****/private static final String BASEPATH = "C:\\tmp\\generator\\";// 獲取項目路徑private static final String ROOTPATH = System.getProperty("user.dir") + "/src/main";private final String WEBPATH = "這里寫上你生成文件的上一級目錄";/*** 一鍵生成*/@Testpublic void generateTest() {// 要生成的beanString[] entities = new String[]{"value"};// 對應的表String[] tables = new String[]{"value"};// Mapper.java文件路徑String path = ROOTPATH + WEBPATH + "*/dao/mapper/?Mapper.java";// baseMapper全限定名String baseMapperQfName = "這里寫上baseMapper的全限定名";generate(entities, tables, path, baseMapperQfName);}/*** 生成Controller,Service, Mapper,xml,bean及其實現** @param entities bean數組* @param tables 生成的表數組* @param mapperPath *的位置代表entity, ?代表對于的大寫格式* @param baseMapperQfName baseMapper全限定名*/private void generate(String[] entities, String[] tables, String mapperPath, String baseMapperQfName) {for (int i = 0; i < entities.length; i++) {System.err.println("==================開始執行第" + (i + 1) + "次=====================");String entity = entities[i];// 生成好對應的xml文件generateForOne(entity, tables[i]);// 如果basePath不存在的話則創建File file = new File(BASEPATH);if (!file.exists()) {file.mkdirs();}// 首先寫好要運行的bat文件writeBat(entity, BASEPATH + entity + ".bat");String path = mapperPath.replace("*", entity).replace("?", StringUtil.capitalize(entity));processMapper(path, entity, baseMapperQfName, !new File(path).exists());generateCtrSerDao(entity);System.err.println("==================結束執行第" + (i + 1) + "次=====================");}}/*** 執行bat命令** @param batPath bat文件路徑*/private Process runCmd(String batPath) {Process process = null;try {process = Runtime.getRuntime().exec("cmd /c C: && start " + batPath);
// InputStream input = process.getInputStream();
// BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// String szline;
// while ((szline = reader.readLine())!= null) {
// System.out.println(szline);
// }
// reader.close();process.waitFor();if (process.exitValue() == 0) {System.err.println("執行bat命令成功");}// 執行成功之后再destroyprocess.destroy();// 執行完畢,關閉本窗口Runtime.getRuntime().exec("cmd.exe /C start wmic process where name='cmd.exe' call terminate");} catch (Exception e) {e.printStackTrace();}return process;}/*** 將命令寫入bat文件** @param entityName 實體名字* @param path 生成bat的路徑*/private void writeBat(String entityName, String path) {String cmd = "java -jar C:\\tmp\\mybatis-generator-core-1.3.2.jar -configfile C:\\tmp\\xml\\" + entityName + ".xml -overwrite";FileOutputStream fileOutputStream = null;try {fileOutputStream = new FileOutputStream(new File(path));fileOutputStream.write(cmd.getBytes());} catch (IOException e) {e.printStackTrace();} finally {StreamUtil.close(fileOutputStream);}}// 根據模板生成對應的xmlprivate void generateForOne(String entityName, String tableName) {String outputPath = "C:\\tmp\\xml";if (!new File(outputPath).exists()) {boolean createDirectoryFlag = new File(outputPath).mkdirs();if (!createDirectoryFlag) {System.err.println("========Danger: mkdirs() error!=========");}}// 獲取對應的版本配置Configuration configuration = new Configuration(Configuration.VERSION_2_3_21);String ftlPath = ROOTPATH + "\\resources\\freemarker";File ftlFilePath = new File(ftlPath);try {// 設置模板文件上級路徑configuration.setDirectoryForTemplateLoading(ftlFilePath);configuration.setDefaultEncoding("UTF-8");// 設置異常處理器configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);// 構建數據模型Map<String, Object> dataMap = new HashMap<>();dataMap.put("entity", entityName);dataMap.put("domain", StringUtil.capitalize(entityName));// 解決不規范命名問題dataMap.put("table", tableName);// 獲取模板Template generatorTemplate = configuration.getTemplate("mapper-generator.ftl");// 設置輸出路徑FileOutputStream fileOutputStream = new FileOutputStream(outputPath + File.separator + entityName + ".xml");OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);generatorTemplate.process(dataMap, outputStreamWriter);} catch (IOException | TemplateException e) {e.printStackTrace();}}/*** 處理mapper.java文件** @param path mapper.java所在路徑* @param entityName* @param baseMapperQfName* @param flag 是否是第一次生成*/private void processMapper(String path, String entityName, String baseMapperQfName, boolean flag) {String backFileName = path + "_backup";if (!flag) {// 首先備份原來的mapper文件FileUtil.copyFile(path, backFileName);}Process process = runCmd(BASEPATH + entityName + ".bat");try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}String mapperContent = getMapperContent(path, entityName, baseMapperQfName, flag);
// System.err.println("生成的Mapper.java文件內容為: \n" + mapperContent);// 將修改后的mapper寫入文件FileUtil.writeToFile(path, mapperContent);File backFile = new File(backFileName);if (backFile.exists()) {boolean delete = backFile.delete();if (!delete) {System.err.println("刪除" + backFileName + "失敗!");}}}/*** 第一次生成, 返回自動產生Mapper文件中的內容,* 非首次生成, 保存原來Mapper.java文件中的方法, 如果未繼承BaseMapper, 則處理為繼承BaseMapper** @param path mapper.java 路徑* @param entityName beanName* @param baseMapperQfName baseMapper全限定名* @param flag 是否是第一次生成* @return 返回生成的Mapper中的String內容*/private String getMapperContent(String path, String entityName, String baseMapperQfName, boolean flag) {// Mapper.java文件路徑String domainName = StringUtil.capitalize(entityName);String url = path + (flag ? "" : "_backup");String separator = System.getProperty("line.separator");// 存儲改動過后的stringStringBuilder buffer = new StringBuilder();FileInputStream fis = null;InputStreamReader reader = null;BufferedReader bufferedReader = null;try {fis = new FileInputStream(new File(url));reader = new InputStreamReader(fis);bufferedReader = new BufferedReader(reader);String str;while ((str = bufferedReader.readLine()) != null) {// 已經import了BaseMapper跳過if (str.contains("mapper.BaseMapper")) continue;// 如果是第一次生成的話if (str.contains("interface")) {buffer.append("import ").append(baseMapperQfName).append(";");// 插入系統的換行符buffer.append(separator);// 格式處理, import 和interface之間添加空行buffer.append(separator);// 處理存在Mapper文件, 但是沒有抽取繼承的情況if (!str.contains("extends BaseMapper")) {String changedText = str.replace(domainName + "Mapper", domainName + "Mapper extends BaseMapper<" + domainName + ">");buffer.append(changedText);}if (flag) {buffer.append(separator);buffer.append("}");break;}}buffer.append(str);buffer.append(separator);}} catch (IOException e) {e.printStackTrace();} finally {StreamUtil.close(bufferedReader, reader, fis);}return buffer.toString();}/*** 生成controller,service,dao** @param entityName beanName*/private void generateCtrSerDao(String entityName) {// 所有模板String[] templateNames = new String[]{"BeanController.ftl", "IBeanService.ftl", "BeanServiceImpl.ftl", "IBeanDao.ftl", "BeanDaoImpl.ftl"};String[] paths = new String[]{"controller/", "service", "service/impl", "dao", "dao/impl"};String[] names = new String[]{"Controller", "Service", "ServiceImpl", "Dao", "DaoImpl"};String domainName = StringUtil.capitalize(entityName);// 獲取對應的版本配置Configuration configuration = new Configuration(Configuration.VERSION_2_3_21);String ftlPath = ROOTPATH + "\\resources\\freemarker";File ftlFilePath = new File(ftlPath);FileOutputStream fileOutputStream = null;OutputStreamWriter outputStreamWriter = null;try {// 設置模板文件上級路徑configuration.setDirectoryForTemplateLoading(ftlFilePath);configuration.setDefaultEncoding("UTF-8");// 設置異常處理器configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);// 構建數據模型Map<String, Object> dataMap = new HashMap<>();dataMap.put("entity", entityName);dataMap.put("domain", domainName);for (int i = 0; i < templateNames.length; i++) {String currFtl = templateNames[i];// 獲取模板Template generatorTemplate = configuration.getTemplate(currFtl);// 設置輸出路徑String outputPath = ROOTPATH + WEBPATH + entityName + "/" + paths[i] + "/" + (i % 2 == 0 ? (domainName + names[i]) : ("I" + domainName + names[i])) + ".java";File file = new File(outputPath);// 判斷一下是否對應的文件是否已經存在,存在的話,不進行替換if (file.exists()) {System.err.println("[" + outputPath + "]" + "已經存在, 不替換");continue;}File parentFile = file.getParentFile();if (!parentFile.exists()) {boolean createDirectoryFlag = parentFile.mkdirs();if (!createDirectoryFlag) {System.err.println("========Danger: mkdirs() error!=========");}}fileOutputStream = new FileOutputStream(outputPath);outputStreamWriter = new OutputStreamWriter(fileOutputStream);generatorTemplate.process(dataMap, outputStreamWriter);System.err.println("-----" + outputPath + "生成成功" + "-----");}} catch (IOException | TemplateException e) {e.printStackTrace();} finally {// 關閉流StreamUtil.close(outputStreamWriter, fileOutputStream);}}}
時間展示處理
這里僅處理兩種不同的日期顯示格式,如果有需要執行配置即可
public class JsonObjectMapper extends ObjectMapper {private static final long serialVersionUID = 1L;public JsonObjectMapper() {super();// 空值處理為空串 this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {@Overridepublic void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException {jg.writeString("");}});//設置JSON時間格式SimpleModule module = new SimpleModule();module.addSerializer(Date.class, new JsonSerializer<Date>() {@Overridepublic void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String zero = "00:00:00";if (zero.equals(sdf.format(value).split(" ")[1])) {sdf = new SimpleDateFormat("yyyy-MM-dd");}jgen.writeString(sdf.format(value));}});this.registerModule(module);}}
同時在spingmvc配置文件中配置:
<mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="objectMapper"><bean class="這里寫JsonObjectMapper全限定名"></bean></property></bean></mvc:message-converters></mvc:annotation-driven>
轉載于:https://www.cnblogs.com/studentytj/p/9328654.html
總結
以上是生活随笔為你收集整理的一些记录的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。