MapperGenerator.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 MapperGenerator {
  14. public static void GenMapper(GenCode model) {
  15. try {
  16. List<String> imports = new ArrayList<>();
  17. imports = GeneratorTool.removeDuplicated(imports);
  18. String templatePath = GetResource.class.getClassLoader().getResource("templates").getPath();
  19. Properties pro = new Properties();
  20. pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
  21. pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
  22. pro.setProperty("directive.foreach.counter.name", "velocityCount");
  23. pro.setProperty("directive.foreach.counter.initial.value", "1");
  24. Velocity.init(pro);
  25. ToolManager manager = new ToolManager(true, true);
  26. VelocityContext context = new VelocityContext(manager.createContext());
  27. context.put("imports", imports);
  28. context.put("model", model);
  29. String templateName = "MapperTemplate.vm";
  30. if ("SqlServer".equals(model.getDataBaseType())) {
  31. templateName = "MapperSqlServerTemplate.vm";
  32. }
  33. Template t = Velocity.getTemplate(templateName);
  34. String targetFile = model.getClassName() + "Mapper.java";
  35. File file = new File(model.getJavaPath() + "/dao", targetFile);
  36. if (!file.getParentFile().exists())
  37. file.getParentFile().mkdirs();
  38. if (!file.exists())
  39. file.createNewFile();
  40. FileOutputStream outStream = new FileOutputStream(file);
  41. OutputStreamWriter writer = new OutputStreamWriter(outStream,
  42. "UTF-8");
  43. BufferedWriter sw = new BufferedWriter(writer);
  44. t.merge(context, sw);
  45. sw.flush();
  46. sw.close();
  47. outStream.close();
  48. System.out.println("成功生成Mapper:" + file.getAbsolutePath());
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }