MapperXmlGenerator.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.izouma.codegenerator;
  2. import com.izouma.awesomeadmin.model.GenCode;
  3. import org.apache.velocity.Template;
  4. import org.apache.velocity.VelocityContext;
  5. import org.apache.velocity.app.Velocity;
  6. import org.apache.velocity.tools.ToolManager;
  7. import org.hibernate.validator.internal.util.privilegedactions.GetResource;
  8. import java.io.BufferedWriter;
  9. import java.io.File;
  10. import java.io.FileOutputStream;
  11. import java.io.OutputStreamWriter;
  12. import java.util.*;
  13. public class MapperXmlGenerator {
  14. public static void GenXml(GenCode model) {
  15. try {
  16. List<String> imports = new ArrayList<>();
  17. String templatePath = GetResource.class.getClassLoader().getResource("templates").getPath();
  18. Properties pro = new Properties();
  19. pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
  20. pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
  21. Velocity.init(pro);
  22. ToolManager manager = new ToolManager(true, true);
  23. VelocityContext context = new VelocityContext(manager.createContext());
  24. context.put("imports", imports);
  25. context.put("model", model);
  26. String templateName = "MapperXmlTemplate.vm";
  27. if ("SqlServer".equals(model.getDataBaseType())) {
  28. templateName = "MapperXmlSqlServerTemplate.vm";
  29. }
  30. Template t = Velocity.getTemplate(templateName);
  31. String targetFile = model.getClassName() + "Mapper.xml";
  32. File file = new File(model.getJavaPath() + "/dao", targetFile);
  33. if (!file.getParentFile().exists())
  34. file.getParentFile().mkdirs();
  35. if (!file.exists())
  36. file.createNewFile();
  37. FileOutputStream outStream = new FileOutputStream(file);
  38. OutputStreamWriter writer = new OutputStreamWriter(outStream,
  39. "UTF-8");
  40. BufferedWriter sw = new BufferedWriter(writer);
  41. t.merge(context, sw);
  42. sw.flush();
  43. sw.close();
  44. outStream.close();
  45. System.out.println("成功生成MapperXml:" + file.getAbsolutePath());
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }