一、简介

在使用mybatis时我们需要重复的去创建pojo类、mapper文件以及dao类并且需要配置它们之间的依赖关系,比较麻烦且做了大量的重复工作,mybatis官方也发现了这个问题,

因此给我们提供了mybatis generator工具来帮我们自动创建pojo类、mapper文件以及dao类并且会帮我们配置好它们的依赖关系

mybatis-geneator是一款mybatis自动代码生成工具,可以通过配置,快速生成mapper和xml文件以及部分dao service controller简单的增删改查以及简单的vue+element ui前端页面,极大的提高了我们的开发效率。

二、maven需要的主要依赖(由于使用springboot模块化开发,依赖太多,不一一列举)

  1. <!-- Velocity视图所需jar -->
  2. <dependency>
  3. <groupId>org.apache.velocity</groupId>
  4. <artifactId>velocity</artifactId>
  5. <version>1.7</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mybatis.generator</groupId>
  9. <artifactId>mybatis-generator-core</artifactId>
  10. <version>1.3.5</version>
  11. </dependency>
  1. <plugin>
  2.  
  3. <groupId>org.mybatis.generator</groupId>
  4.  
  5. <artifactId>mybatis-generator-maven-plugin</artifactId>
  6.  
  7. <version>1.3.2</version>
  8.  
  9. <executions>
  10.  
  11. <execution>
  12.  
  13. <id>Generate MyBatis Files</id>
  14.  
  15. <goals>
  16.  
  17. <goal>generate</goal>
  18.  
  19. </goals>
  20.  
  21. <phase>generate</phase>
  22.  
  23. <configuration>
  24.  
  25. <verbose>true</verbose>
  26.  
  27. <overwrite>true</overwrite>
  28.  
  29. </configuration>
  30.  
  31. </execution>
  32.  
  33. </executions>

三、generator.properties配置文件(本案例数据库只有一个表)

  1. # generator.controller.module 可以设置为空,为空不生成代码
  2. generator.controller.module=project-web
  3. # generator.service.module 可以设置为空,为空不生成代码
  4. generator.service.module=project-service
  5. # generator.dao.module 不允许为空
  6. generator.dao.module=project-dao
  7. generator.controller.package.prefix=edu.nf.project
  8. generator.service.package.prefix=edu.nf.project
  9. generator.dao.package.prefix=edu.nf.project
  10. generator.table.prefix=city_
  11. generator.table.list=
  12. generator.database=weather
  13. generator.jdbc.driver=com.mysql.cj.jdbc.Driver
  14. generator.jdbc.url=jdbc:mysql://localhost:3306/weather?useSSL=false&useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&serverTimezone=UTC
  15. generator.jdbc.username=root
  16. generator.jdbc.password=root

四、生成模块代码工具类(并生成简单的Vue页面)

  1. public class MybatisGeneratorUtil {
  2. public MybatisGeneratorUtil() {
  3. }
  4.  
  5. public static void generator(String jdbcDriver, String jdbcUrl, String jdbcUsername, String jdbcPassword, String controllerModule, String serviceModule, String daoModule, String database, String tablePrefix, String tableList, String controllerPackagePrefix, String servicePackagePrefix, String daoPackagePrefix, Map<String, String> lastInsertIdTables) throws Exception {
  6. String generatorConfigVm = "/template/generatorConfig.vm";
  7. String serviceVm = "/template/Service.vm";
  8. String daoVm = "/template/Dao.vm";
  9. String serviceMockVm = "/template/ServiceMock.vm";
  10. String serviceImplVm = "/template/ServiceImpl.vm";
  11. String controllerVm = "/template/Controller.vm";
  12. String vueListVm = "/template/vue/List.vm";
  13. String vueEditVm = "/template/vue/Edit.vm";
  14. String vueApiVm = "/template/vue/Api.vm";
  15. String ctime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
  16. String basePath = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "").replace("/target/test-classes/", "").replaceFirst(daoModule, "").replaceFirst("/", "");
  17. String sql = "SELECT table_name,TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = ? AND table_name LIKE ?";
  18. String columnSql = "SELECT COLUMN_NAME,COLUMN_COMMENT,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?";
  19. String keySql = "SELECT COLUMN_NAME,COLUMN_COMMENT,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_KEY = 'PRI'";
  20. System.out.println("========== 开始生成generatorConfig.xml文件 ==========");
  21. List<Map<String, Object>> tables = new ArrayList();
  22. VelocityContext context = new VelocityContext();
  23. HashMap table;
  24. JdbcUtil jdbcUtil;
  25. String[] tablePrefixs;
  26. int var34;
  27. if (!StringUtils.isEmpty(tablePrefix)) {
  28. tablePrefixs = tablePrefix.split(",");
  29. String[] var33 = tablePrefixs;
  30. var34 = tablePrefixs.length;
  31.  
  32. for(int var35 = ; var35 < var34; ++var35) {
  33. String str = var33[var35];
  34. jdbcUtil = new JdbcUtil(jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword);
  35. List<Map> result = jdbcUtil.selectByParams(sql, Arrays.asList(database, str + "%"));
  36. Iterator var38 = result.iterator();
  37.  
  38. while(var38.hasNext()) {
  39. Map map = (Map)var38.next();
  40. System.out.println(map.get("TABLE_NAME"));
  41. table = new HashMap();
  42. table.put("table_name", map.get("TABLE_NAME"));
  43. table.put("table_comment", map.get("TABLE_COMMENT"));
  44. table.put("model_name", StringUtil.lineToHump(ObjectUtils.toString(map.get("TABLE_NAME"))));
  45. tables.add(table);
  46. }
  47.  
  48. jdbcUtil.release();
  49. }
  50. }
  51.  
  52. if (!StringUtils.isEmpty(tableList)) {
  53. tablePrefixs = tableList.split(",");
  54. int var71 = tablePrefixs.length;
  55.  
  56. for(var34 = ; var34 < var71; ++var34) {
  57. String tableName = tablePrefixs[var34];
  58. table = new HashMap();
  59. table.put("table_name", tableName);
  60. table.put("model_name", StringUtil.lineToHump(tableName));
  61. tables.add(table);
  62. }
  63. }
  64.  
  65. String daoTargetProject = basePath + daoModule;
  66. context.put("tables", tables);
  67. context.put("generator_javaModelGenerator_targetPackage", daoPackagePrefix + ".model");
  68. context.put("generator_sqlMapGenerator_targetPackage", "mappers");
  69. context.put("generator_javaClientGenerator_targetPackage", daoPackagePrefix + ".mapper");
  70. context.put("targetProject", daoTargetProject);
  71. context.put("targetProject_sqlMap", daoTargetProject);
  72. context.put("generator_jdbc_password", jdbcPassword);
  73. context.put("last_insert_id_tables", lastInsertIdTables);
  74. InputStream generatorConfigInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(generatorConfigVm);
  75. String generatorConfigXML = VelocityUtil.generate(generatorConfigInputSteam, context);
  76. System.out.println(generatorConfigXML);
  77. deleteDir(new File(daoTargetProject + "/src/main/java/" + daoPackagePrefix.replaceAll("\\.", "/") + "/model"));
  78. deleteDir(new File(daoTargetProject + "/src/main/java/" + daoPackagePrefix.replaceAll("\\.", "/") + "/mapper"));
  79. deleteDir(new File(daoTargetProject + "/src/main/resources/mappers"));
  80. System.out.println("========== 结束生成generatorConfig.xml文件 ==========");
  81. System.out.println("========== 开始运行MybatisGenerator ==========");
  82. List<String> warnings = new ArrayList();
  83. ConfigurationParser cp = new ConfigurationParser(warnings);
  84. Configuration config = cp.parseConfiguration(new StringReader(generatorConfigXML));
  85. DefaultShellCallback callback = new DefaultShellCallback(true);
  86. MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
  87. myBatisGenerator.generate((ProgressCallback)null);
  88. Iterator var40 = warnings.iterator();
  89.  
  90. String serviceTargetProject;
  91. while(var40.hasNext()) {
  92. serviceTargetProject = (String)var40.next();
  93. System.out.println(serviceTargetProject);
  94. }
  95.  
  96. System.out.println("========== 结束运行MybatisGenerator ==========");
  97. System.out.println("========== 开始生成dao ==========");
  98. String daoPath = daoTargetProject + "/src/main/java/" + daoPackagePrefix.replaceAll("\\.", "/") + "/dao";
  99. (new File(daoPath)).mkdirs();
  100. Iterator var81 = tables.iterator();
  101.  
  102. String serviceImplPath;
  103. String controllerTargetProject;
  104. String controllerPath;
  105. while(var81.hasNext()) {
  106. Map<String, Object> table1 = (Map)var81.next();
  107. serviceImplPath = StringUtil.lineToHump(ObjectUtils.toString(table1.get("table_name")));
  108. controllerTargetProject = ObjectUtils.toString(table1.get("table_comment"));
  109. controllerPath = daoPath + "/" + serviceImplPath + "Dao.java";
  110. VelocityContext tempContext = new VelocityContext();
  111. tempContext.put("dao_package_prefix", daoPackagePrefix);
  112. tempContext.put("model", serviceImplPath);
  113. tempContext.put("modelname", controllerTargetProject);
  114. tempContext.put("mapper", StringUtil.toLowerCaseFirstOne(serviceImplPath));
  115. tempContext.put("ctime", ctime);
  116. File serviceFile = new File(controllerPath);
  117. if (!serviceFile.exists()) {
  118. InputStream daoInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(daoVm);
  119. VelocityUtil.generate(daoInputSteam, controllerPath, tempContext);
  120. System.out.println(controllerPath);
  121. }
  122. }
  123.  
  124. System.out.println("========== 结束生成dao ==========");
  125. System.out.println("========== 开始生成Service ==========");
  126. serviceTargetProject = basePath + serviceModule;
  127. String servicePath = serviceTargetProject + "/src/main/java/" + servicePackagePrefix.replaceAll("\\.", "/") + "/service";
  128. serviceImplPath = serviceTargetProject + "/src/main/java/" + servicePackagePrefix.replaceAll("\\.", "/") + "/service/impl";
  129. (new File(serviceImplPath)).mkdirs();
  130. Iterator var83 = tables.iterator();
  131.  
  132. String vuePagePath;
  133. String searchPath;
  134. String vueTargetProject;
  135. String vueApiPath;
  136. while(var83.hasNext()) {
  137. Map<String, Object> table1 = (Map)var83.next();
  138. searchPath = StringUtil.lineToHump(ObjectUtils.toString(table1.get("table_name")));
  139. vueTargetProject = ObjectUtils.toString(table1.get("table_comment"));
  140. vueApiPath = servicePath + "/" + searchPath + "Service.java";
  141. vuePagePath = serviceImplPath + "/" + searchPath + "ServiceImpl.java";
  142. VelocityContext tempContext = new VelocityContext();
  143. tempContext.put("service_package_prefix", servicePackagePrefix);
  144. tempContext.put("dao_package_prefix", daoPackagePrefix);
  145. tempContext.put("model", searchPath);
  146. tempContext.put("modelname", vueTargetProject);
  147. tempContext.put("mapper", StringUtil.toLowerCaseFirstOne(searchPath));
  148. tempContext.put("ctime", ctime);
  149. File serviceFile = new File(vueApiPath);
  150. if (!serviceFile.exists()) {
  151. InputStream serviceInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(serviceVm);
  152. VelocityUtil.generate(serviceInputSteam, vueApiPath, tempContext);
  153. System.out.println(vueApiPath);
  154. }
  155.  
  156. File serviceImplFile = new File(vuePagePath);
  157. if (!serviceImplFile.exists()) {
  158. InputStream serviceImplInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(serviceImplVm);
  159. VelocityUtil.generate(serviceImplInputSteam, vuePagePath, tempContext);
  160. System.out.println(vuePagePath);
  161. }
  162. }
  163.  
  164. System.out.println("========== 结束生成Service ==========");
  165. System.out.println("========== 开始生成Controller 和 vue ==========");
  166. controllerTargetProject = basePath + controllerModule;
  167. controllerPath = controllerTargetProject + "/src/main/java/" + controllerPackagePrefix.replaceAll("\\.", "/") + "/controller";
  168. searchPath = controllerTargetProject + "/src/main/java/" + controllerPackagePrefix.replaceAll("\\.", "/") + "/dto/search";
  169. vueTargetProject = basePath + daoModule;
  170. vueApiPath = vueTargetProject + "/vue/api";
  171. vuePagePath = vueTargetProject + "/vue/page";
  172. (new File(controllerPath)).mkdirs();
  173. (new File(searchPath)).mkdirs();
  174. (new File(vueApiPath)).mkdirs();
  175. (new File(vuePagePath)).mkdirs();
  176.  
  177. String model;
  178. for(Iterator var88 = tables.iterator(); var88.hasNext(); System.out.println("========== 结束生成[" + model + "]vue页面 ==========")) {
  179. Map<String, Object> table1 = (Map)var88.next();
  180. List<Object> sqlParams = Arrays.asList(database, table1.get("table_name"));
  181. List<Map<String, Object>> columns = new ArrayList();
  182. jdbcUtil = new JdbcUtil(jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword);
  183. List<Map> columnResult = jdbcUtil.selectByParams(columnSql, sqlParams);
  184. Iterator var55 = columnResult.iterator();
  185.  
  186. while(var55.hasNext()) {
  187. Map map = (Map)var55.next();
  188. Map<String, Object> column = new HashMap();
  189. column.put("column_comment", map.get("COLUMN_COMMENT"));
  190. column.put("column_name", StringUtil.toLowerCaseFirstOne(StringUtil.lineToHump(ObjectUtils.toString(map.get("COLUMN_NAME")))));
  191. column.put("data_type", map.get("DATA_TYPE"));
  192. columns.add(column);
  193. }
  194.  
  195. Map<String, Object> key = new HashMap();
  196. List<Map> keyResult = jdbcUtil.selectByParams(keySql, sqlParams);
  197. if (!CollectionUtils.isEmpty(keyResult)) {
  198. Map map = (Map)keyResult.get();
  199. key.put("column_comment", map.get("COLUMN_COMMENT"));
  200. key.put("column_name", StringUtil.lineToHump(ObjectUtils.toString(map.get("COLUMN_NAME"))));
  201. key.put("data_type", map.get("DATA_TYPE"));
  202. }
  203.  
  204. jdbcUtil.release();
  205. model = StringUtil.lineToHump(ObjectUtils.toString(table1.get("table_name")));
  206. String modelName = ObjectUtils.toString(table1.get("table_comment"));
  207. VelocityContext tempContext = new VelocityContext();
  208. tempContext.put("controller_package_prefix", controllerPackagePrefix);
  209. tempContext.put("service_package_prefix", servicePackagePrefix);
  210. tempContext.put("dao_package_prefix", daoPackagePrefix);
  211. tempContext.put("key", key);
  212. tempContext.put("columns", columns);
  213. tempContext.put("model", model);
  214. tempContext.put("modelname", modelName);
  215. tempContext.put("mapper", StringUtil.toLowerCaseFirstOne(model));
  216. tempContext.put("ctime", ctime);
  217. String controller = controllerPath + "/" + model + "Controller.java";
  218. String search = searchPath + "/" + model + "Search.java";
  219. String vueApi = vueApiPath + "/" + model + "Api.js";
  220. String vueList = vuePagePath + "/" + model + "/" + model + "List.vue";
  221. String vueEdit = vuePagePath + "/" + model + "/" + model + "Edit.vue";
  222. (new File(vuePagePath + "/" + model)).mkdirs();
  223. System.out.println("========== 开始生成[" + model + "]Controller ==========");
  224. File controllerFile = new File(controller);
  225. if (!controllerFile.exists()) {
  226. InputStream controllerInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(controllerVm);
  227. VelocityUtil.generate(controllerInputSteam, controller, tempContext);
  228. System.out.println(controller);
  229. }
  230.  
  231. System.out.println("========== 结束生成[" + model + "]Controller ==========");
  232. System.out.println("========== 开始生成[" + model + "]vue页面 ==========");
  233. File vueApiFile = new File(vueApi);
  234. if (!vueApiFile.exists()) {
  235. InputStream vueInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(vueApiVm);
  236. VelocityUtil.generate(vueInputSteam, vueApi, tempContext);
  237. System.out.println(vueApi);
  238. }
  239.  
  240. File vueListFile = new File(vueList);
  241. if (!vueListFile.exists()) {
  242. InputStream searchVmInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(vueListVm);
  243. VelocityUtil.generate(searchVmInputSteam, vueList, tempContext);
  244. System.out.println(vueList);
  245. }
  246.  
  247. File vueEditFile = new File(vueEdit);
  248. if (!vueEditFile.exists()) {
  249. InputStream searchVmInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(vueEditVm);
  250. VelocityUtil.generate(searchVmInputSteam, vueEdit, tempContext);
  251. System.out.println(vueEdit);
  252. }
  253. }
  254.  
  255. System.out.println("========== 结束生成Controller 和 vue ==========");
  256. }
  257.  
  258. private static void deleteDir(File dir) {
  259. if (dir.isDirectory()) {
  260. File[] files = dir.listFiles();
  261. if (files != null) {
  262. File[] var2 = files;
  263. int var3 = files.length;
  264.  
  265. for(int var4 = ; var4 < var3; ++var4) {
  266. File file = var2[var4];
  267. deleteDir(file);
  268. }
  269. }
  270. }
  271.  
  272. dir.delete();
  273. }
  274. }

五、生成器(Generator)

  1. /**
  2. * 代码生成类
  3. *
  4. * @author ywb
  5. */
  6. public class Generator {
  7. private static String CONTROLLER_MODULE = PropertiesFileUtil.getInstance("generator").get("generator.controller.module");
  8. private static String SERVICE_MODULE = PropertiesFileUtil.getInstance("generator").get("generator.service.module");
  9. private static String DAO_MODULE = PropertiesFileUtil.getInstance("generator").get("generator.dao.module");
  10. private static String CONTROLLER_PACKAGE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.controller.package.prefix");
  11. private static String SERVICE_PACKAGE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.service.package.prefix");
  12. private static String DAO_PACKAGE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.dao.package.prefix");
  13. private static String TABLE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.table.prefix");
  14. private static String TABLE_LIST = PropertiesFileUtil.getInstance("generator").get("generator.table.list");
  15. private static String DATABASE = PropertiesFileUtil.getInstance("generator").get("generator.database");
  16. private static String JDBC_DRIVER = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.driver");
  17. private static String JDBC_URL = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.url");
  18. private static String JDBC_USERNAME = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.username");
  19. private static String JDBC_PASSWORD = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.password");
  20. /**
  21. * 需要insert后返回主键的表配置,key:表名,value:主键名
  22. */
  23. private static Map<String, String> LAST_INSERT_ID_TABLES = new HashMap<>();/**
  24. * 自动代码生成
  25. */
  26. public static void main(String[] args) throws Exception {
  27. MybatisGeneratorUtil.generator(JDBC_DRIVER, JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD,
  28. CONTROLLER_MODULE, SERVICE_MODULE, DAO_MODULE,
  29. DATABASE, TABLE_PREFIX, TABLE_LIST,
  30. CONTROLLER_PACKAGE_PREFIX, SERVICE_PACKAGE_PREFIX, DAO_PACKAGE_PREFIX,
  31. LAST_INSERT_ID_TABLES);
  32. }

六、自动生成出来的mapper

  1. package edu.nf.project.mapper;
  2.  
  3. import edu.nf.project.model.CityInfo;
  4. import edu.nf.project.model.CityInfoExample;
  5. import java.util.List;
  6. import org.apache.ibatis.annotations.Param;
  7.  
  8. public interface CityInfoMapper {
  9. long countByExample(CityInfoExample example);
  10.  
  11. int deleteByExample(CityInfoExample example);
  12.  
  13. int deleteByPrimaryKey(Integer cityId);
  14.  
  15. int insert(CityInfo record);
  16.  
  17. int insertSelective(CityInfo record);
  18.  
  19. List<CityInfo> selectByExample(CityInfoExample example);
  20.  
  21. CityInfo selectByPrimaryKey(Integer cityId);
  22.  
  23. int updateByExampleSelective(@Param("record") CityInfo record, @Param("example") CityInfoExample example);
  24.  
  25. int updateByExample(@Param("record") CityInfo record, @Param("example") CityInfoExample example);
  26.  
  27. int updateByPrimaryKeySelective(CityInfo record);
  28.  
  29. int updateByPrimaryKey(CityInfo record);
  30. }

七、自动生成出来的Model

  1. package edu.nf.project.model;
  2.  
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import java.io.Serializable;
  6. import org.springframework.format.annotation.DateTimeFormat;
  7.  
  8. /**
  9. *
  10. * city_info
  11. *
  12. * @mbg.generated
  13. */
  14. public class CityInfo implements Serializable {
  15. /**
  16. * 城市编号
  17. *
  18. * city_info.city_id
  19. */
  20. @ApiModelProperty(value = "城市编号")
  21. private Integer cityId;
  22.  
  23. /**
  24. * 城市名称
  25. *
  26. * city_info.city_name
  27. */
  28. @ApiModelProperty(value = "城市名称")
  29. private String cityName;
  30.  
  31. /**
  32. * 城市编码
  33. *
  34. * city_info.city_code
  35. */
  36. @ApiModelProperty(value = "城市编码")
  37. private String cityCode;
  38.  
  39. /**
  40. * 省份
  41. *
  42. * city_info.province
  43. */
  44. @ApiModelProperty(value = "省份")
  45. private String province;
  46.  
  47. private static final long serialVersionUID = 1L;
  48.  
  49. public Integer getCityId() {
  50. return cityId;
  51. }
  52.  
  53. public void setCityId(Integer cityId) {
  54. this.cityId = cityId;
  55. }
  56.  
  57. public String getCityName() {
  58. return cityName;
  59. }
  60.  
  61. public void setCityName(String cityName) {
  62. this.cityName = cityName == null ? null : cityName.trim();
  63. }
  64.  
  65. public String getCityCode() {
  66. return cityCode;
  67. }
  68.  
  69. public void setCityCode(String cityCode) {
  70. this.cityCode = cityCode == null ? null : cityCode.trim();
  71. }
  72.  
  73. public String getProvince() {
  74. return province;
  75. }
  76.  
  77. public void setProvince(String province) {
  78. this.province = province == null ? null : province.trim();
  79. }
  80.  
  81. @Override
  82. public String toString() {
  83. StringBuilder sb = new StringBuilder();
  84. sb.append(getClass().getSimpleName());
  85. sb.append(" [");
  86. sb.append("Hash = ").append(hashCode());
  87. sb.append(", cityId=").append(cityId);
  88. sb.append(", cityName=").append(cityName);
  89. sb.append(", cityCode=").append(cityCode);
  90. sb.append(", province=").append(province);
  91. sb.append("]");
  92. return sb.toString();
  93. }
  94.  
  95. @Override
  96. public boolean equals(Object that) {
  97. if (this == that) {
  98. return true;
  99. }
  100. if (that == null) {
  101. return false;
  102. }
  103. if (getClass() != that.getClass()) {
  104. return false;
  105. }
  106. CityInfo other = (CityInfo) that;
  107. return (this.getCityId() == null ? other.getCityId() == null : this.getCityId().equals(other.getCityId()))
  108. && (this.getCityName() == null ? other.getCityName() == null : this.getCityName().equals(other.getCityName()))
  109. && (this.getCityCode() == null ? other.getCityCode() == null : this.getCityCode().equals(other.getCityCode()))
  110. && (this.getProvince() == null ? other.getProvince() == null : this.getProvince().equals(other.getProvince()));
  111. }
  112.  
  113. @Override
  114. public int hashCode() {
  115. final int prime = 31;
  116. int result = 1;
  117. result = prime * result + ((getCityId() == null) ? 0 : getCityId().hashCode());
  118. result = prime * result + ((getCityName() == null) ? 0 : getCityName().hashCode());
  119. result = prime * result + ((getCityCode() == null) ? 0 : getCityCode().hashCode());
  120. result = prime * result + ((getProvince() == null) ? 0 : getProvince().hashCode());
  121. return result;
  122. }
  123. }
  1. package edu.nf.project.model;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. public class CityInfoExample {
  7. protected String orderByClause;
  8.  
  9. protected boolean distinct;
  10.  
  11. protected List<Criteria> oredCriteria;
  12.  
  13. public CityInfoExample() {
  14. oredCriteria = new ArrayList<Criteria>();
  15. }
  16.  
  17. public void setOrderByClause(String orderByClause) {
  18. this.orderByClause = orderByClause;
  19. }
  20.  
  21. public String getOrderByClause() {
  22. return orderByClause;
  23. }
  24.  
  25. public void setDistinct(boolean distinct) {
  26. this.distinct = distinct;
  27. }
  28.  
  29. public boolean isDistinct() {
  30. return distinct;
  31. }
  32.  
  33. public List<Criteria> getOredCriteria() {
  34. return oredCriteria;
  35. }
  36.  
  37. public void or(Criteria criteria) {
  38. oredCriteria.add(criteria);
  39. }
  40.  
  41. public Criteria or() {
  42. Criteria criteria = createCriteriaInternal();
  43. oredCriteria.add(criteria);
  44. return criteria;
  45. }
  46.  
  47. public Criteria createCriteria() {
  48. Criteria criteria = createCriteriaInternal();
  49. if (oredCriteria.size() == 0) {
  50. oredCriteria.add(criteria);
  51. }
  52. return criteria;
  53. }
  54.  
  55. protected Criteria createCriteriaInternal() {
  56. Criteria criteria = new Criteria();
  57. return criteria;
  58. }
  59.  
  60. public void clear() {
  61. oredCriteria.clear();
  62. orderByClause = null;
  63. distinct = false;
  64. }
  65.  
  66. protected abstract static class GeneratedCriteria {
  67. protected List<Criterion> criteria;
  68.  
  69. protected GeneratedCriteria() {
  70. super();
  71. criteria = new ArrayList<Criterion>();
  72. }
  73.  
  74. public boolean isValid() {
  75. return criteria.size() > 0;
  76. }
  77.  
  78. public List<Criterion> getAllCriteria() {
  79. return criteria;
  80. }
  81.  
  82. public List<Criterion> getCriteria() {
  83. return criteria;
  84. }
  85.  
  86. protected void addCriterion(String condition) {
  87. if (condition == null) {
  88. throw new RuntimeException("Value for condition cannot be null");
  89. }
  90. criteria.add(new Criterion(condition));
  91. }
  92.  
  93. protected void addCriterion(String condition, Object value, String property) {
  94. if (value == null) {
  95. throw new RuntimeException("Value for " + property + " cannot be null");
  96. }
  97. criteria.add(new Criterion(condition, value));
  98. }
  99.  
  100. protected void addCriterion(String condition, Object value1, Object value2, String property) {
  101. if (value1 == null || value2 == null) {
  102. throw new RuntimeException("Between values for " + property + " cannot be null");
  103. }
  104. criteria.add(new Criterion(condition, value1, value2));
  105. }
  106.  
  107. public Criteria andCityIdIsNull() {
  108. addCriterion("city_id is null");
  109. return (Criteria) this;
  110. }
  111.  
  112. public Criteria andCityIdIsNotNull() {
  113. addCriterion("city_id is not null");
  114. return (Criteria) this;
  115. }
  116.  
  117. public Criteria andCityIdEqualTo(Integer value) {
  118. addCriterion("city_id =", value, "cityId");
  119. return (Criteria) this;
  120. }
  121.  
  122. public Criteria andCityIdNotEqualTo(Integer value) {
  123. addCriterion("city_id <>", value, "cityId");
  124. return (Criteria) this;
  125. }
  126.  
  127. public Criteria andCityIdGreaterThan(Integer value) {
  128. addCriterion("city_id >", value, "cityId");
  129. return (Criteria) this;
  130. }
  131.  
  132. public Criteria andCityIdGreaterThanOrEqualTo(Integer value) {
  133. addCriterion("city_id >=", value, "cityId");
  134. return (Criteria) this;
  135. }
  136.  
  137. public Criteria andCityIdLessThan(Integer value) {
  138. addCriterion("city_id <", value, "cityId");
  139. return (Criteria) this;
  140. }
  141.  
  142. public Criteria andCityIdLessThanOrEqualTo(Integer value) {
  143. addCriterion("city_id <=", value, "cityId");
  144. return (Criteria) this;
  145. }
  146.  
  147. public Criteria andCityIdIn(List<Integer> values) {
  148. addCriterion("city_id in", values, "cityId");
  149. return (Criteria) this;
  150. }
  151.  
  152. public Criteria andCityIdNotIn(List<Integer> values) {
  153. addCriterion("city_id not in", values, "cityId");
  154. return (Criteria) this;
  155. }
  156.  
  157. public Criteria andCityIdBetween(Integer value1, Integer value2) {
  158. addCriterion("city_id between", value1, value2, "cityId");
  159. return (Criteria) this;
  160. }
  161.  
  162. public Criteria andCityIdNotBetween(Integer value1, Integer value2) {
  163. addCriterion("city_id not between", value1, value2, "cityId");
  164. return (Criteria) this;
  165. }
  166.  
  167. public Criteria andCityNameIsNull() {
  168. addCriterion("city_name is null");
  169. return (Criteria) this;
  170. }
  171.  
  172. public Criteria andCityNameIsNotNull() {
  173. addCriterion("city_name is not null");
  174. return (Criteria) this;
  175. }
  176.  
  177. public Criteria andCityNameEqualTo(String value) {
  178. addCriterion("city_name =", value, "cityName");
  179. return (Criteria) this;
  180. }
  181.  
  182. public Criteria andCityNameNotEqualTo(String value) {
  183. addCriterion("city_name <>", value, "cityName");
  184. return (Criteria) this;
  185. }
  186.  
  187. public Criteria andCityNameGreaterThan(String value) {
  188. addCriterion("city_name >", value, "cityName");
  189. return (Criteria) this;
  190. }
  191.  
  192. public Criteria andCityNameGreaterThanOrEqualTo(String value) {
  193. addCriterion("city_name >=", value, "cityName");
  194. return (Criteria) this;
  195. }
  196.  
  197. public Criteria andCityNameLessThan(String value) {
  198. addCriterion("city_name <", value, "cityName");
  199. return (Criteria) this;
  200. }
  201.  
  202. public Criteria andCityNameLessThanOrEqualTo(String value) {
  203. addCriterion("city_name <=", value, "cityName");
  204. return (Criteria) this;
  205. }
  206.  
  207. public Criteria andCityNameLike(String value) {
  208. addCriterion("city_name like", value, "cityName");
  209. return (Criteria) this;
  210. }
  211.  
  212. public Criteria andCityNameNotLike(String value) {
  213. addCriterion("city_name not like", value, "cityName");
  214. return (Criteria) this;
  215. }
  216.  
  217. public Criteria andCityNameIn(List<String> values) {
  218. addCriterion("city_name in", values, "cityName");
  219. return (Criteria) this;
  220. }
  221.  
  222. public Criteria andCityNameNotIn(List<String> values) {
  223. addCriterion("city_name not in", values, "cityName");
  224. return (Criteria) this;
  225. }
  226.  
  227. public Criteria andCityNameBetween(String value1, String value2) {
  228. addCriterion("city_name between", value1, value2, "cityName");
  229. return (Criteria) this;
  230. }
  231.  
  232. public Criteria andCityNameNotBetween(String value1, String value2) {
  233. addCriterion("city_name not between", value1, value2, "cityName");
  234. return (Criteria) this;
  235. }
  236.  
  237. public Criteria andCityCodeIsNull() {
  238. addCriterion("city_code is null");
  239. return (Criteria) this;
  240. }
  241.  
  242. public Criteria andCityCodeIsNotNull() {
  243. addCriterion("city_code is not null");
  244. return (Criteria) this;
  245. }
  246.  
  247. public Criteria andCityCodeEqualTo(String value) {
  248. addCriterion("city_code =", value, "cityCode");
  249. return (Criteria) this;
  250. }
  251.  
  252. public Criteria andCityCodeNotEqualTo(String value) {
  253. addCriterion("city_code <>", value, "cityCode");
  254. return (Criteria) this;
  255. }
  256.  
  257. public Criteria andCityCodeGreaterThan(String value) {
  258. addCriterion("city_code >", value, "cityCode");
  259. return (Criteria) this;
  260. }
  261.  
  262. public Criteria andCityCodeGreaterThanOrEqualTo(String value) {
  263. addCriterion("city_code >=", value, "cityCode");
  264. return (Criteria) this;
  265. }
  266.  
  267. public Criteria andCityCodeLessThan(String value) {
  268. addCriterion("city_code <", value, "cityCode");
  269. return (Criteria) this;
  270. }
  271.  
  272. public Criteria andCityCodeLessThanOrEqualTo(String value) {
  273. addCriterion("city_code <=", value, "cityCode");
  274. return (Criteria) this;
  275. }
  276.  
  277. public Criteria andCityCodeLike(String value) {
  278. addCriterion("city_code like", value, "cityCode");
  279. return (Criteria) this;
  280. }
  281.  
  282. public Criteria andCityCodeNotLike(String value) {
  283. addCriterion("city_code not like", value, "cityCode");
  284. return (Criteria) this;
  285. }
  286.  
  287. public Criteria andCityCodeIn(List<String> values) {
  288. addCriterion("city_code in", values, "cityCode");
  289. return (Criteria) this;
  290. }
  291.  
  292. public Criteria andCityCodeNotIn(List<String> values) {
  293. addCriterion("city_code not in", values, "cityCode");
  294. return (Criteria) this;
  295. }
  296.  
  297. public Criteria andCityCodeBetween(String value1, String value2) {
  298. addCriterion("city_code between", value1, value2, "cityCode");
  299. return (Criteria) this;
  300. }
  301.  
  302. public Criteria andCityCodeNotBetween(String value1, String value2) {
  303. addCriterion("city_code not between", value1, value2, "cityCode");
  304. return (Criteria) this;
  305. }
  306.  
  307. public Criteria andProvinceIsNull() {
  308. addCriterion("province is null");
  309. return (Criteria) this;
  310. }
  311.  
  312. public Criteria andProvinceIsNotNull() {
  313. addCriterion("province is not null");
  314. return (Criteria) this;
  315. }
  316.  
  317. public Criteria andProvinceEqualTo(String value) {
  318. addCriterion("province =", value, "province");
  319. return (Criteria) this;
  320. }
  321.  
  322. public Criteria andProvinceNotEqualTo(String value) {
  323. addCriterion("province <>", value, "province");
  324. return (Criteria) this;
  325. }
  326.  
  327. public Criteria andProvinceGreaterThan(String value) {
  328. addCriterion("province >", value, "province");
  329. return (Criteria) this;
  330. }
  331.  
  332. public Criteria andProvinceGreaterThanOrEqualTo(String value) {
  333. addCriterion("province >=", value, "province");
  334. return (Criteria) this;
  335. }
  336.  
  337. public Criteria andProvinceLessThan(String value) {
  338. addCriterion("province <", value, "province");
  339. return (Criteria) this;
  340. }
  341.  
  342. public Criteria andProvinceLessThanOrEqualTo(String value) {
  343. addCriterion("province <=", value, "province");
  344. return (Criteria) this;
  345. }
  346.  
  347. public Criteria andProvinceLike(String value) {
  348. addCriterion("province like", value, "province");
  349. return (Criteria) this;
  350. }
  351.  
  352. public Criteria andProvinceNotLike(String value) {
  353. addCriterion("province not like", value, "province");
  354. return (Criteria) this;
  355. }
  356.  
  357. public Criteria andProvinceIn(List<String> values) {
  358. addCriterion("province in", values, "province");
  359. return (Criteria) this;
  360. }
  361.  
  362. public Criteria andProvinceNotIn(List<String> values) {
  363. addCriterion("province not in", values, "province");
  364. return (Criteria) this;
  365. }
  366.  
  367. public Criteria andProvinceBetween(String value1, String value2) {
  368. addCriterion("province between", value1, value2, "province");
  369. return (Criteria) this;
  370. }
  371.  
  372. public Criteria andProvinceNotBetween(String value1, String value2) {
  373. addCriterion("province not between", value1, value2, "province");
  374. return (Criteria) this;
  375. }
  376. }
  377.  
  378. public static class Criteria extends GeneratedCriteria {
  379.  
  380. protected Criteria() {
  381. super();
  382. }
  383. }
  384.  
  385. public static class Criterion {
  386. private String condition;
  387.  
  388. private Object value;
  389.  
  390. private Object secondValue;
  391.  
  392. private boolean noValue;
  393.  
  394. private boolean singleValue;
  395.  
  396. private boolean betweenValue;
  397.  
  398. private boolean listValue;
  399.  
  400. private String typeHandler;
  401.  
  402. public String getCondition() {
  403. return condition;
  404. }
  405.  
  406. public Object getValue() {
  407. return value;
  408. }
  409.  
  410. public Object getSecondValue() {
  411. return secondValue;
  412. }
  413.  
  414. public boolean isNoValue() {
  415. return noValue;
  416. }
  417.  
  418. public boolean isSingleValue() {
  419. return singleValue;
  420. }
  421.  
  422. public boolean isBetweenValue() {
  423. return betweenValue;
  424. }
  425.  
  426. public boolean isListValue() {
  427. return listValue;
  428. }
  429.  
  430. public String getTypeHandler() {
  431. return typeHandler;
  432. }
  433.  
  434. protected Criterion(String condition) {
  435. super();
  436. this.condition = condition;
  437. this.typeHandler = null;
  438. this.noValue = true;
  439. }
  440.  
  441. protected Criterion(String condition, Object value, String typeHandler) {
  442. super();
  443. this.condition = condition;
  444. this.value = value;
  445. this.typeHandler = typeHandler;
  446. if (value instanceof List<?>) {
  447. this.listValue = true;
  448. } else {
  449. this.singleValue = true;
  450. }
  451. }
  452.  
  453. protected Criterion(String condition, Object value) {
  454. this(condition, value, null);
  455. }
  456.  
  457. protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
  458. super();
  459. this.condition = condition;
  460. this.value = value;
  461. this.secondValue = secondValue;
  462. this.typeHandler = typeHandler;
  463. this.betweenValue = true;
  464. }
  465.  
  466. protected Criterion(String condition, Object value, Object secondValue) {
  467. this(condition, value, secondValue, null);
  468. }
  469. }
  470. }

七、自动生成XML文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="edu.nf.project.mapper.CityInfoMapper">
  4. <resultMap id="BaseResultMap" type="edu.nf.project.model.CityInfo">
  5. <id column="city_id" jdbcType="INTEGER" property="cityId" />
  6. <result column="city_name" jdbcType="VARCHAR" property="cityName" />
  7. <result column="city_code" jdbcType="VARCHAR" property="cityCode" />
  8. <result column="province" jdbcType="VARCHAR" property="province" />
  9. </resultMap>
  10. <sql id="Example_Where_Clause">
  11. <where>
  12. <foreach collection="oredCriteria" item="criteria" separator="or">
  13. <if test="criteria.valid">
  14. <trim prefix="(" prefixOverrides="and" suffix=")">
  15. <foreach collection="criteria.criteria" item="criterion">
  16. <choose>
  17. <when test="criterion.noValue">
  18. and ${criterion.condition}
  19. </when>
  20. <when test="criterion.singleValue">
  21. and ${criterion.condition} #{criterion.value}
  22. </when>
  23. <when test="criterion.betweenValue">
  24. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  25. </when>
  26. <when test="criterion.listValue">
  27. and ${criterion.condition}
  28. <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
  29. #{listItem}
  30. </foreach>
  31. </when>
  32. </choose>
  33. </foreach>
  34. </trim>
  35. </if>
  36. </foreach>
  37. </where>
  38. </sql>
  39. <sql id="Update_By_Example_Where_Clause">
  40. <where>
  41. <foreach collection="example.oredCriteria" item="criteria" separator="or">
  42. <if test="criteria.valid">
  43. <trim prefix="(" prefixOverrides="and" suffix=")">
  44. <foreach collection="criteria.criteria" item="criterion">
  45. <choose>
  46. <when test="criterion.noValue">
  47. and ${criterion.condition}
  48. </when>
  49. <when test="criterion.singleValue">
  50. and ${criterion.condition} #{criterion.value}
  51. </when>
  52. <when test="criterion.betweenValue">
  53. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  54. </when>
  55. <when test="criterion.listValue">
  56. and ${criterion.condition}
  57. <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
  58. #{listItem}
  59. </foreach>
  60. </when>
  61. </choose>
  62. </foreach>
  63. </trim>
  64. </if>
  65. </foreach>
  66. </where>
  67. </sql>
  68. <sql id="Base_Column_List">
  69. city_id, city_name, city_code, province
  70. </sql>
  71. <select id="selectByExample" parameterType="edu.nf.project.model.CityInfoExample" resultMap="BaseResultMap">
  72. select
  73. <if test="distinct">
  74. distinct
  75. </if>
  76. <include refid="Base_Column_List" />
  77. from city_info
  78. <if test="_parameter != null">
  79. <include refid="Example_Where_Clause" />
  80. </if>
  81. <if test="orderByClause != null">
  82. order by ${orderByClause}
  83. </if>
  84. </select>
  85. <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
  86. select
  87. <include refid="Base_Column_List" />
  88. from city_info
  89. where city_id = #{cityId,jdbcType=INTEGER}
  90. </select>
  91. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
  92. delete from city_info
  93. where city_id = #{cityId,jdbcType=INTEGER}
  94. </delete>
  95. <delete id="deleteByExample" parameterType="edu.nf.project.model.CityInfoExample">
  96. delete from city_info
  97. <if test="_parameter != null">
  98. <include refid="Example_Where_Clause" />
  99. </if>
  100. </delete>
  101. <insert id="insert" parameterType="edu.nf.project.model.CityInfo">
  102. insert into city_info (city_id, city_name, city_code,
  103. province)
  104. values (#{cityId,jdbcType=INTEGER}, #{cityName,jdbcType=VARCHAR}, #{cityCode,jdbcType=VARCHAR},
  105. #{province,jdbcType=VARCHAR})
  106. </insert>
  107. <insert id="insertSelective" parameterType="edu.nf.project.model.CityInfo">
  108. insert into city_info
  109. <trim prefix="(" suffix=")" suffixOverrides=",">
  110. <if test="cityId != null">
  111. city_id,
  112. </if>
  113. <if test="cityName != null">
  114. city_name,
  115. </if>
  116. <if test="cityCode != null">
  117. city_code,
  118. </if>
  119. <if test="province != null">
  120. province,
  121. </if>
  122. </trim>
  123. <trim prefix="values (" suffix=")" suffixOverrides=",">
  124. <if test="cityId != null">
  125. #{cityId,jdbcType=INTEGER},
  126. </if>
  127. <if test="cityName != null">
  128. #{cityName,jdbcType=VARCHAR},
  129. </if>
  130. <if test="cityCode != null">
  131. #{cityCode,jdbcType=VARCHAR},
  132. </if>
  133. <if test="province != null">
  134. #{province,jdbcType=VARCHAR},
  135. </if>
  136. </trim>
  137. </insert>
  138. <select id="countByExample" parameterType="edu.nf.project.model.CityInfoExample" resultType="java.lang.Long">
  139. select count(*) from city_info
  140. <if test="_parameter != null">
  141. <include refid="Example_Where_Clause" />
  142. </if>
  143. </select>
  144. <update id="updateByExampleSelective" parameterType="map">
  145. update city_info
  146. <set>
  147. <if test="record.cityId != null">
  148. city_id = #{record.cityId,jdbcType=INTEGER},
  149. </if>
  150. <if test="record.cityName != null">
  151. city_name = #{record.cityName,jdbcType=VARCHAR},
  152. </if>
  153. <if test="record.cityCode != null">
  154. city_code = #{record.cityCode,jdbcType=VARCHAR},
  155. </if>
  156. <if test="record.province != null">
  157. province = #{record.province,jdbcType=VARCHAR},
  158. </if>
  159. </set>
  160. <if test="_parameter != null">
  161. <include refid="Update_By_Example_Where_Clause" />
  162. </if>
  163. </update>
  164. <update id="updateByExample" parameterType="map">
  165. update city_info
  166. set city_id = #{record.cityId,jdbcType=INTEGER},
  167. city_name = #{record.cityName,jdbcType=VARCHAR},
  168. city_code = #{record.cityCode,jdbcType=VARCHAR},
  169. province = #{record.province,jdbcType=VARCHAR}
  170. <if test="_parameter != null">
  171. <include refid="Update_By_Example_Where_Clause" />
  172. </if>
  173. </update>
  174. <update id="updateByPrimaryKeySelective" parameterType="edu.nf.project.model.CityInfo">
  175. update city_info
  176. <set>
  177. <if test="cityName != null">
  178. city_name = #{cityName,jdbcType=VARCHAR},
  179. </if>
  180. <if test="cityCode != null">
  181. city_code = #{cityCode,jdbcType=VARCHAR},
  182. </if>
  183. <if test="province != null">
  184. province = #{province,jdbcType=VARCHAR},
  185. </if>
  186. </set>
  187. where city_id = #{cityId,jdbcType=INTEGER}
  188. </update>
  189. <update id="updateByPrimaryKey" parameterType="edu.nf.project.model.CityInfo">
  190. update city_info
  191. set city_name = #{cityName,jdbcType=VARCHAR},
  192. city_code = #{cityCode,jdbcType=VARCHAR},
  193. province = #{province,jdbcType=VARCHAR}
  194. where city_id = #{cityId,jdbcType=INTEGER}
  195. </update>
  196. </mapper>

八、以及service dao controller(这里只复制controller)

  1. package edu.nf.project.controller;
  2.  
  3. import com.wang.common.base.BaseController;
  4. import com.wang.common.model.base.result.DataResult;
  5. import com.wang.common.uitl.IdGenerator;
  6. import com.wang.common.model.page.PageInfoResult;
  7. import com.wang.common.model.page.PageParam;
  8. import edu.nf.project.model.CityInfo;
  9. import edu.nf.project.model.CityInfoExample;
  10. import edu.nf.project.service.CityInfoService;
  11. import com.github.pagehelper.PageInfo;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import io.swagger.annotations.Api;
  15. import io.swagger.annotations.ApiOperation;
  16. import org.apache.shiro.authz.annotation.RequiresPermissions;
  17. import org.springframework.web.bind.annotation.*;
  18.  
  19. import javax.annotation.Resource;
  20. import java.util.List;
  21.  
  22. /**
  23. * controller
  24. * Created by Administrator on 2019-06-20T11:55:04.44.
  25. *
  26. * @author Administrator
  27. */
  28. @RestController
  29. @ResponseBody
  30. @RequestMapping(value = "/cityInfo")
  31. @Api(value = "控制器", description = "管理")
  32. public class CityInfoController extends BaseController {
  33.  
  34. private static final Logger LOGGER = LoggerFactory.getLogger(CityInfoController.class);
  35.  
  36. @Resource
  37. private CityInfoService cityInfoService;
  38.  
  39. /**
  40. * 列表
  41. *
  42. * @param pageParam 分页参数
  43. * @return DataResult
  44. */
  45. @GetMapping(value = "/list")
  46. @ApiOperation(value = "列表")
  47. public PageInfoResult<CityInfo> list(PageParam pageParam) {
  48. CityInfoExample cityInfoExample = new CityInfoExample();
  49. List<CityInfo> cityInfoList = cityInfoService.selectByExampleForStartPage(cityInfoExample, pageParam.getPageNum(), pageParam.getPageSize());
  50. long total = cityInfoService.countByExample(cityInfoExample);
  51. return new PageInfoResult<>(cityInfoList, total);
  52. }
  53.  
  54. /**
  55. * 添加
  56. *
  57. * @param cityInfo 数据
  58. * @return DataResult
  59. */
  60. @PostMapping(value = "/add")
  61. @ApiOperation(value = "添加")
  62. @RequiresPermissions("cityInfo:add")
  63. public DataResult add(@RequestBody CityInfo cityInfo) {
  64. cityInfo.setCityId((int)(IdGenerator.getId()));
  65. cityInfoService.insertSelective(cityInfo);
  66. return new DataResult("success", "保存成功");
  67. }
  68.  
  69. /**
  70. * 删除
  71. *
  72. * @param id 主键
  73. * @return DataResult
  74. */
  75. @GetMapping(value = "/delete")
  76. @ApiOperation(value = "删除")
  77. @RequiresPermissions("cityInfo:delete")
  78. public DataResult delete(Long id) {
  79. cityInfoService.deleteByPrimaryKey(id);
  80. return new DataResult("success", "删除成功");
  81. }
  82.  
  83. /**
  84. * 修改
  85. *
  86. * @param cityInfo 数据
  87. * @return DataResult
  88. */
  89. @PostMapping(value = "/update")
  90. @ApiOperation(value = "修改")
  91. @RequiresPermissions("cityInfo:update")
  92. public DataResult update(@RequestBody CityInfo cityInfo) {
  93. CityInfoExample cityInfoExample = new CityInfoExample();
  94. cityInfoExample.createCriteria().andCityIdEqualTo(cityInfo.getCityId());
  95. cityInfoService.updateByExampleSelective(cityInfo, cityInfoExample);
  96. return new DataResult("success", "修改成功");
  97. }
  98.  
  99. /**
  100. * 详情
  101. *
  102. * @param id 主键
  103. * @return DataResult
  104. */
  105. @GetMapping(value = "/detail")
  106. @ApiOperation(value = "详情")
  107. @RequiresPermissions("cityInfo:detail")
  108. public DataResult<CityInfo> detail(Long id) {
  109. CityInfo cityInfo = cityInfoService.selectByPrimaryKey(id);
  110. return new DataResult<>(cityInfo);
  111. }
  112.  
  113. }

九:生成标准的vue页面和vue.js文件

  1. // api
  2. // Created by Administrator on 2019-06-20T10:55:15.236.
  3. import request from '@/utils/requestJson'
  4.  
  5. // 查找数据
  6. export const listApi = params => {
  7. return request.get('/cityInfo/list', { params: params })
  8. }
  9. // 添加数据
  10. export const addApi = params => {
  11. return request.post('/cityInfo/add', params)
  12. }
  13. // 修改数据
  14. export const updateApi = params => {
  15. return request.post('/cityInfo/update', params)
  16. }
  17. // 删除数据
  18. export const deleteApi = params => {
  19. return request.get('/cityInfo/delete', { params: params })
  20. }
  21. // 详细数据
  22. export const detailApi = params => {
  23. return request.get('/cityInfo/detail', { params: params })
  24. }
  1. // 编辑
  2. // Created by Administrator on 2019-06-20T10:55:15.236.
  3. <template>
  4. <el-dialog class="add-permission" title="编辑" :visible.sync="dialogVisible" width="500px"
  5. :close-on-click-modal="false" :before-close="handleClose">
  6. <el-form ref="dataForm" size="small" :rules="rules" :model="dataForm" label-width="80px">
  7. <el-form-item label="" prop="cityId">
  8. <el-input size="small" v-model="dataForm.cityId" type="text"/>
  9. </el-form-item>
  10. <el-form-item label="" prop="cityName">
  11. <el-input size="small" v-model="dataForm.cityName" type="text"/>
  12. </el-form-item>
  13. <el-form-item label="" prop="cityCode">
  14. <el-input size="small" v-model="dataForm.cityCode" type="text"/>
  15. </el-form-item>
  16. <el-form-item label="" prop="province">
  17. <el-input size="small" v-model="dataForm.province" type="text"/>
  18. </el-form-item>
  19. </el-form>
  20.  
  21. <span slot="footer" class="dialog-footer">
  22. <el-button @click="dialogVisible = false" size="small">取 消</el-button>
  23. <el-button type="primary" size="small" :loading="loading" @click="saveData">保存</el-button>
  24. </span>
  25. </el-dialog>
  26. </template>
  27.  
  28. <script>
  29. import { addApi, detailApi, updateApi } from '@/api/cityInfoApi'
  30.  
  31. class CityInfo {
  32. constructor () {
  33. this.cityId = null
  34. this.cityName = null
  35. this.cityCode = null
  36. this.province = null
  37. }
  38.  
  39. set cityInfo (cityInfo) {
  40. this.cityId = cityInfo.cityId
  41. this.cityName = cityInfo.cityName
  42. this.cityCode = cityInfo.cityCode
  43. this.province = cityInfo.province
  44. }
  45. }
  46.  
  47. export default {
  48. data () {
  49. return {
  50. dialogVisible: false,
  51. loading: false,
  52. dataForm: new CityInfo(),
  53. rules: {
  54. systemId: [{ required: true, message: '请选择系统', trigger: 'blur' }],
  55. title: [{ required: true, message: '请填写权限名称', trigger: 'blur' }],
  56. type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  57. permissionValue: [
  58. { required: true, message: '请填写权限值', trigger: 'blur' }
  59. ]
  60. }
  61. }
  62. },
  63. methods: {
  64. showDialog (id) {
  65. this.dialogVisible = true
  66. if (id) {
  67. detailApi({ id: id }).then(res => {
  68. this.dataForm.cityInfo = res.data
  69. })
  70. }
  71. },
  72. handleClose () {
  73. this.dialogVisible = false
  74. },
  75. // 保存数据
  76. saveData () {
  77. let refs = this.$refs
  78. refs.dataForm.validate(valid => {
  79. if (valid) {
  80. this.loading = true
  81. let api
  82. if (this.dataForm.id) {
  83. api = updateApi(this.dataForm)
  84. } else {
  85. api = addApi(this.dataForm)
  86. }
  87. api.then(res => {
  88. this.$message({ type: 'success', message: res.sub_msg })
  89. this.dialogVisible = false
  90. this.$emit('callback')
  91. }).finally(() => {
  92. this.loading = false
  93. })
  94. }
  95. })
  96. }
  97. }
  98. }
  99. </script>
  1. // 列表
  2. // Created by Administrator on 2019-06-20T10:55:15.236.
  3. <template>
  4. <div class="app-container">
  5. <!--搜索条件-->
  6. <div class="filter-container">
  7. <el-input placeholder="请输入内容" v-model="listQuery.title" style="width: 200px;" @keyup.enter.native="listSearch"
  8. size="small" clearable/>
  9. <el-button type="primary" icon="el-icon-search" @click="listSearch" size="small">查询</el-button>
  10. <el-button type="primary" icon="el-icon-edit" @click="addClick" v-if="hasPerm('upms:permManage:addPerm')"
  11. style="margin-left:0;" size="small">添加
  12. </el-button>
  13. </div>
  14. <!--表格-->
  15. <div class="table-container">
  16. <el-table
  17. :data="rows"
  18. border
  19. fit
  20. size="small"
  21. highlight-current-row
  22. style="width: 100%;"
  23. v-loading="loading">
  24. <!-- 需要映射的表 -->
  25. <el-table-column prop="cityId" label="" align="left" width="150" show-overflow-tooltip/>
  26. <el-table-column prop="cityName" label="" align="left" width="150" show-overflow-tooltip/>
  27. <el-table-column prop="cityCode" label="" align="left" width="150" show-overflow-tooltip/>
  28. <el-table-column prop="province" label="" align="left" width="150" show-overflow-tooltip/>
  29.  
  30. <el-table-column label="操作" align="left" fixed="right" width="150">
  31. <template slot-scope="scope">
  32. <el-button type="primary" @click="editClick(scope.row.CityId)" v-if="hasPerm('upms:permManage:editPerm')"
  33. size="mini">编辑
  34. </el-button>
  35. <el-button type="danger" @click="deleteClick(scope.row.CityId)"
  36. v-if="hasPerm('upms:permManage:delPerm')" size="mini">删除
  37. </el-button>
  38. </template>
  39. </el-table-column>
  40. </el-table>
  41. <!--分页-->
  42. <el-pagination
  43. @size-change="handleSizeChange"
  44. @current-change="handleCurrentChange"
  45. :current-page="listQuery.pageNum"
  46. :page-sizes="[10, 20, 30, 40, 50]"
  47. :page-size="listQuery.pageSize"
  48. layout="total, sizes, prev, pager, next, jumper"
  49. :total="total">
  50. </el-pagination>
  51. </div>
  52. <!--添加、修改组件-->
  53. <CityInfoEdit ref="cityInfoEditRef" @callback="listSearch"/>
  54. </div>
  55. </template>
  56. <script>
  57. import { deleteApi, listApi } from '@/api/cityInfoApi'
  58. import CityInfoEdit from './CityInfoEdit'
  59.  
  60. export default {
  61. components: { CityInfoEdit },
  62. data () {
  63. return {
  64. loading: false,
  65. rows: [],
  66. listQuery: {
  67. systemId: null,
  68. title: null,
  69. permType: null,
  70. pageNum: 1,
  71. pageSize: 10
  72. },
  73. total: 0
  74. }
  75. },
  76. mounted () {
  77. this.listSearch()
  78. },
  79. methods: {
  80. listSearch () {
  81. this.loading = true
  82. listApi(this.listQuery).then(res => {
  83. this.total = Number(res.total)
  84. this.rows = res.list
  85. }).finally(() => {
  86. this.loading = false
  87. })
  88. },
  89. addClick () {
  90. this.$refs.cityInfoEditRef.showDialog(this.listQuery.systemId)
  91. },
  92. editClick (id) {
  93. this.$refs.cityInfoEditRef.showDialog(id)
  94. },
  95. deleteClick (id) {
  96. this.$confirm('确定删除数据?', '提示', {
  97. confirmButtonText: '确定',
  98. cancelButtonText: '取消',
  99. type: 'warning'
  100. }).then(() => {
  101. deleteApi({ id: id }).then(res => {
  102. this.$message({ type: 'success', message: res.sub_msg })
  103. this.listSearch()
  104. })
  105. })
  106. },
  107. // 分页相关
  108. handleSizeChange (val) {
  109. this.listQuery.pageSize = val
  110. this.listSearch()
  111. },
  112. // 分页相关
  113. handleCurrentChange (val) {
  114. this.listQuery.pageNum = val
  115. this.listSearch()
  116. }
  117. }
  118. }
  119. </script>

十、配图(本案例用springboot 项目构建,模块化开发)

mybatis-geneator的更多相关文章

  1. MyBatis Geneator详解<转>

    MyBatis Geneator中文文档地址: http://generator.sturgeon.mopaas.com/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看中文版的文档的 ...

  2. mybatis.generator.configurationFile

    mybatis.generator.configurationFile 有一个更好的配置方法,可以不用在generateConfig.xml里面写死驱动的地址:如果你的mybatis连接也是在pom. ...

  3. Spring boot后台搭建一使用MyBatis集成Mapper和PageHelper

    目标: 使用 Spring  boot+MyBatis+mysql 集成 Mapper 和 PageHelper,实现基本的增删改查 先建一个基本的 Spring Boot 项目开启 Spring B ...

  4. MyBatis-Generator最佳实践

    引用地址:http://arccode.net/2015/02/07/MyBatis-Generator%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5/ 最近使用MyBati ...

  5. spring-boot-通用mapper

    数据源依赖 druid官方文档:https://github.com/alibaba/druid/wiki/常见问题 <dependency> <groupId>mysql&l ...

  6. 一步一步教你用IntelliJ IDEA 搭建SSM框架(2)——配置mybatis-geneator

    我们要搭建整个SSM框架,所以要继续上篇文章没有完成的工作,下面配置mybatis-geneator,自动生成mybatis代码. 在上篇文章中的pom.xml的配置文件中已经加了mybatis-ge ...

  7. 【分享】标准springMVC+mybatis项目maven搭建最精简教程

    文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...

  8. Java MyBatis 插入数据库返回主键

    最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...

  9. [原创]mybatis中整合ehcache缓存框架的使用

    mybatis整合ehcache缓存框架的使用 mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓 ...

  10. 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程

    本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...

随机推荐

  1. .net软件日常开发规范-基本标准

    一. 基本标准 代码和SQL脚本均不要出现无意义的空格和空行. 所有SQL脚本确保可以重复运行不出错,添加数据的脚本重复运行不会重复添加数据. 能用一行代码或脚本解决的不要写出两行,能用一个方法解决的 ...

  2. 【程序人生】从湖北省最早的四位java高级工程师之一到出家为僧所引发的深思

           从我刚上大学接触程序员这个职业开始,到如今我从事了七年多程序员,这期间我和我的不少小伙伴接受了太多的负面信息,在成长的道路上也真了交了不少的情商税.这些负面信息中,有一件就是我大学班主任 ...

  3. SpringMVC源码分析6:SpringMVC的视图解析原理

    title: SpringMVC源码分析6:SpringMVC的视图解析原理 date: 2018-06-07 11:03:19 tags: - SpringMVC categories: - 后端 ...

  4. SpringCloud阶段总结

    学习时间:8.15 -- 8.29 学习目标:了解SpringCloud常见组件的使用 学习方式: 输入:视频+博客+开源项目代码参考 输出:调试代码+写博客输出 组件列表 服务注册:Eureka 客 ...

  5. 详解golang net之transport

    关于golang http transport的讲解,网上有很多文章读它进行了描述,但很多文章讲的都比较粗,很多代码实现并没有讲清楚.故给出更加详细的实现说明.整体看下来细节实现层面还是比较难懂的. ...

  6. MSIL实用指南-生成内部类

    生成内部类用TypeBuilder的DefineNestedType方法,得到另一个TypeBuilder.内部类的可访问性都是TypeAttributes的“Nested”开头一些成员.实例代码:y ...

  7. CAS及其ABA问题

    CAS.volatile是JUC包实现同步的基础.Synchronized下的偏向锁.轻量级锁的获取.释放,lock机制下锁的获取.释放,获取失败后线程的入队等操作都是CAS操作锁标志位.state. ...

  8. mysql安装-yum方式

    1.环境 查看当前系统环境,使用的是 centos release 6.5 (Final). 2.检查当前系统是否已经安装过mysql rpm -qa | grep mysql 3.如果有,那么删除已 ...

  9. net core天马行空系列: 泛型仓储和声明式事物实现最优雅的crud操作

    系列目录 1.net core天马行空系列:原生DI+AOP实现spring boot注解式编程 哈哈哈哈,大家好,我就是那个高产似母猪的三合,长久以来,我一直在思考,如何才能实现高效而简洁的仓储模式 ...

  10. HTML(二)属性,标题,段落,文本格式化

    HTML属性 HTML属性 HTML 元素可以设置属性 属性可以在元素中添加附加信息 属性一般描述于开始标签 属性总是以名称/值对的形式出现,比如:name="value" 常用属 ...