springboot模块化开发+mybatis-geneator+velocity(自动生成代码和vue页面+element ui)


一、简介

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

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

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

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

 

<!-- Velocity视图所需jar -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
<plugin>

           <groupId>org.mybatis.generator</groupId>

           <artifactId>mybatis-generator-maven-plugin</artifactId>

           <version>1.3.2</version>

           <executions>

              <execution>

                 <id>Generate MyBatis Files</id>

                 <goals>

                    <goal>generate</goal>

                 </goals>

                 <phase>generate</phase>

                 <configuration>

                    <verbose>true</verbose>

                    <overwrite>true</overwrite>

                 </configuration>

              </execution>

           </executions>

 

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

# generator.controller.module 可以设置为空,为空不生成代码 generator.controller.module=project-web # generator.service.module 可以设置为空,为空不生成代码 generator.service.module=project-service # generator.dao.module 不允许为空 generator.dao.module=project-dao generator.controller.package.prefix=edu.nf.project generator.service.package.prefix=edu.nf.project generator.dao.package.prefix=edu.nf.project generator.table.prefix=city_ generator.table.list= generator.database=weather generator.jdbc.driver=com.mysql.cj.jdbc.Driver generator.jdbc.url=jdbc:mysql://localhost:3306/weather?useSSL=false&useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&serverTimezone=UTC generator.jdbc.username=root generator.jdbc.password=root

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

 

public class MybatisGeneratorUtil { public MybatisGeneratorUtil() { } 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 { String generatorConfigVm = "/template/generatorConfig.vm"; String serviceVm = "/template/Service.vm"; String daoVm = "/template/Dao.vm"; String serviceMockVm = "/template/ServiceMock.vm"; String serviceImplVm = "/template/ServiceImpl.vm"; String controllerVm = "/template/Controller.vm"; String vueListVm = "/template/vue/List.vm"; String vueEditVm = "/template/vue/Edit.vm"; String vueApiVm = "/template/vue/Api.vm"; String ctime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); String basePath = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "").replace("/target/test-classes/", "").replaceFirst(daoModule, "").replaceFirst("/", ""); String sql = "SELECT table_name,TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = ? AND table_name LIKE ?"; String columnSql = "SELECT COLUMN_NAME,COLUMN_COMMENT,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?"; String keySql = "SELECT COLUMN_NAME,COLUMN_COMMENT,DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_KEY = 'PRI'"; System.out.println("========== 开始生成generatorConfig.xml文件 =========="); List<Map<String, Object>> tables = new ArrayList(); VelocityContext context = new VelocityContext(); HashMap table; JdbcUtil jdbcUtil; String[] tablePrefixs; int var34; if (!StringUtils.isEmpty(tablePrefix)) { tablePrefixs = tablePrefix.split(","); String[] var33 = tablePrefixs; var34 = tablePrefixs.length; for(int var35 = 0; var35 < var34; ++var35) { String str = var33[var35]; jdbcUtil = new JdbcUtil(jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword); List<Map> result = jdbcUtil.selectByParams(sql, Arrays.asList(database, str + "%")); Iterator var38 = result.iterator(); while(var38.hasNext()) { Map map = (Map)var38.next(); System.out.println(map.get("TABLE_NAME")); table = new HashMap(3); table.put("table_name", map.get("TABLE_NAME")); table.put("table_comment", map.get("TABLE_COMMENT")); table.put("model_name", StringUtil.lineToHump(ObjectUtils.toString(map.get("TABLE_NAME")))); tables.add(table); } jdbcUtil.release(); } } if (!StringUtils.isEmpty(tableList)) { tablePrefixs = tableList.split(","); int var71 = tablePrefixs.length; for(var34 = 0; var34 < var71; ++var34) { String tableName = tablePrefixs[var34]; table = new HashMap(2); table.put("table_name", tableName); table.put("model_name", StringUtil.lineToHump(tableName)); tables.add(table); } } String daoTargetProject = basePath + daoModule; context.put("tables", tables); context.put("generator_javaModelGenerator_targetPackage", daoPackagePrefix + ".model"); context.put("generator_sqlMapGenerator_targetPackage", "mappers"); context.put("generator_javaClientGenerator_targetPackage", daoPackagePrefix + ".mapper"); context.put("targetProject", daoTargetProject); context.put("targetProject_sqlMap", daoTargetProject); context.put("generator_jdbc_password", jdbcPassword); context.put("last_insert_id_tables", lastInsertIdTables); InputStream generatorConfigInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(generatorConfigVm); String generatorConfigXML = VelocityUtil.generate(generatorConfigInputSteam, context); System.out.println(generatorConfigXML); deleteDir(new File(daoTargetProject + "/src/main/java/" + daoPackagePrefix.replaceAll("\\.", "/") + "/model")); deleteDir(new File(daoTargetProject + "/src/main/java/" + daoPackagePrefix.replaceAll("\\.", "/") + "/mapper")); deleteDir(new File(daoTargetProject + "/src/main/resources/mappers")); System.out.println("========== 结束生成generatorConfig.xml文件 =========="); System.out.println("========== 开始运行MybatisGenerator =========="); List<String> warnings = new ArrayList(); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(new StringReader(generatorConfigXML)); DefaultShellCallback callback = new DefaultShellCallback(true); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate((ProgressCallback)null); Iterator var40 = warnings.iterator(); String serviceTargetProject; while(var40.hasNext()) { serviceTargetProject = (String)var40.next(); System.out.println(serviceTargetProject); } System.out.println("========== 结束运行MybatisGenerator =========="); System.out.println("========== 开始生成dao =========="); String daoPath = daoTargetProject + "/src/main/java/" + daoPackagePrefix.replaceAll("\\.", "/") + "/dao"; (new File(daoPath)).mkdirs(); Iterator var81 = tables.iterator(); String serviceImplPath; String controllerTargetProject; String controllerPath; while(var81.hasNext()) { Map<String, Object> table1 = (Map)var81.next(); serviceImplPath = StringUtil.lineToHump(ObjectUtils.toString(table1.get("table_name"))); controllerTargetProject = ObjectUtils.toString(table1.get("table_comment")); controllerPath = daoPath + "/" + serviceImplPath + "Dao.java"; VelocityContext tempContext = new VelocityContext(); tempContext.put("dao_package_prefix", daoPackagePrefix); tempContext.put("model", serviceImplPath); tempContext.put("modelname", controllerTargetProject); tempContext.put("mapper", StringUtil.toLowerCaseFirstOne(serviceImplPath)); tempContext.put("ctime", ctime); File serviceFile = new File(controllerPath); if (!serviceFile.exists()) { InputStream daoInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(daoVm); VelocityUtil.generate(daoInputSteam, controllerPath, tempContext); System.out.println(controllerPath); } } System.out.println("========== 结束生成dao =========="); System.out.println("========== 开始生成Service =========="); serviceTargetProject = basePath + serviceModule; String servicePath = serviceTargetProject + "/src/main/java/" + servicePackagePrefix.replaceAll("\\.", "/") + "/service"; serviceImplPath = serviceTargetProject + "/src/main/java/" + servicePackagePrefix.replaceAll("\\.", "/") + "/service/impl"; (new File(serviceImplPath)).mkdirs(); Iterator var83 = tables.iterator(); String vuePagePath; String searchPath; String vueTargetProject; String vueApiPath; while(var83.hasNext()) { Map<String, Object> table1 = (Map)var83.next(); searchPath = StringUtil.lineToHump(ObjectUtils.toString(table1.get("table_name"))); vueTargetProject = ObjectUtils.toString(table1.get("table_comment")); vueApiPath = servicePath + "/" + searchPath + "Service.java"; vuePagePath = serviceImplPath + "/" + searchPath + "ServiceImpl.java"; VelocityContext tempContext = new VelocityContext(); tempContext.put("service_package_prefix", servicePackagePrefix); tempContext.put("dao_package_prefix", daoPackagePrefix); tempContext.put("model", searchPath); tempContext.put("modelname", vueTargetProject); tempContext.put("mapper", StringUtil.toLowerCaseFirstOne(searchPath)); tempContext.put("ctime", ctime); File serviceFile = new File(vueApiPath); if (!serviceFile.exists()) { InputStream serviceInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(serviceVm); VelocityUtil.generate(serviceInputSteam, vueApiPath, tempContext); System.out.println(vueApiPath); } File serviceImplFile = new File(vuePagePath); if (!serviceImplFile.exists()) { InputStream serviceImplInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(serviceImplVm); VelocityUtil.generate(serviceImplInputSteam, vuePagePath, tempContext); System.out.println(vuePagePath); } } System.out.println("========== 结束生成Service =========="); System.out.println("========== 开始生成Controller 和 vue =========="); controllerTargetProject = basePath + controllerModule; controllerPath = controllerTargetProject + "/src/main/java/" + controllerPackagePrefix.replaceAll("\\.", "/") + "/controller"; searchPath = controllerTargetProject + "/src/main/java/" + controllerPackagePrefix.replaceAll("\\.", "/") + "/dto/search"; vueTargetProject = basePath + daoModule; vueApiPath = vueTargetProject + "/vue/api"; vuePagePath = vueTargetProject + "/vue/page"; (new File(controllerPath)).mkdirs(); (new File(searchPath)).mkdirs(); (new File(vueApiPath)).mkdirs(); (new File(vuePagePath)).mkdirs(); String model; for(Iterator var88 = tables.iterator(); var88.hasNext(); System.out.println("========== 结束生成[" + model + "]vue页面 ==========")) { Map<String, Object> table1 = (Map)var88.next(); List<Object> sqlParams = Arrays.asList(database, table1.get("table_name")); List<Map<String, Object>> columns = new ArrayList(); jdbcUtil = new JdbcUtil(jdbcDriver, jdbcUrl, jdbcUsername, jdbcPassword); List<Map> columnResult = jdbcUtil.selectByParams(columnSql, sqlParams); Iterator var55 = columnResult.iterator(); while(var55.hasNext()) { Map map = (Map)var55.next(); Map<String, Object> column = new HashMap(3); column.put("column_comment", map.get("COLUMN_COMMENT")); column.put("column_name", StringUtil.toLowerCaseFirstOne(StringUtil.lineToHump(ObjectUtils.toString(map.get("COLUMN_NAME"))))); column.put("data_type", map.get("DATA_TYPE")); columns.add(column); } Map<String, Object> key = new HashMap(2); List<Map> keyResult = jdbcUtil.selectByParams(keySql, sqlParams); if (!CollectionUtils.isEmpty(keyResult)) { Map map = (Map)keyResult.get(0); key.put("column_comment", map.get("COLUMN_COMMENT")); key.put("column_name", StringUtil.lineToHump(ObjectUtils.toString(map.get("COLUMN_NAME")))); key.put("data_type", map.get("DATA_TYPE")); } jdbcUtil.release(); model = StringUtil.lineToHump(ObjectUtils.toString(table1.get("table_name"))); String modelName = ObjectUtils.toString(table1.get("table_comment")); VelocityContext tempContext = new VelocityContext(); tempContext.put("controller_package_prefix", controllerPackagePrefix); tempContext.put("service_package_prefix", servicePackagePrefix); tempContext.put("dao_package_prefix", daoPackagePrefix); tempContext.put("key", key); tempContext.put("columns", columns); tempContext.put("model", model); tempContext.put("modelname", modelName); tempContext.put("mapper", StringUtil.toLowerCaseFirstOne(model)); tempContext.put("ctime", ctime); String controller = controllerPath + "/" + model + "Controller.java"; String search = searchPath + "/" + model + "Search.java"; String vueApi = vueApiPath + "/" + model + "Api.js"; String vueList = vuePagePath + "/" + model + "/" + model + "List.vue"; String vueEdit = vuePagePath + "/" + model + "/" + model + "Edit.vue"; (new File(vuePagePath + "/" + model)).mkdirs(); System.out.println("========== 开始生成[" + model + "]Controller =========="); File controllerFile = new File(controller); if (!controllerFile.exists()) { InputStream controllerInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(controllerVm); VelocityUtil.generate(controllerInputSteam, controller, tempContext); System.out.println(controller); } System.out.println("========== 结束生成[" + model + "]Controller =========="); System.out.println("========== 开始生成[" + model + "]vue页面 =========="); File vueApiFile = new File(vueApi); if (!vueApiFile.exists()) { InputStream vueInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(vueApiVm); VelocityUtil.generate(vueInputSteam, vueApi, tempContext); System.out.println(vueApi); } File vueListFile = new File(vueList); if (!vueListFile.exists()) { InputStream searchVmInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(vueListVm); VelocityUtil.generate(searchVmInputSteam, vueList, tempContext); System.out.println(vueList); } File vueEditFile = new File(vueEdit); if (!vueEditFile.exists()) { InputStream searchVmInputSteam = MybatisGeneratorUtil.class.getResourceAsStream(vueEditVm); VelocityUtil.generate(searchVmInputSteam, vueEdit, tempContext); System.out.println(vueEdit); } } System.out.println("========== 结束生成Controller 和 vue =========="); } private static void deleteDir(File dir) { if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { File[] var2 = files; int var3 = files.length; for(int var4 = 0; var4 < var3; ++var4) { File file = var2[var4]; deleteDir(file); } } } dir.delete(); } }

五、生成器(Generator)

/** * 代码生成类 * * @author ywb */
public class Generator { private static String CONTROLLER_MODULE = PropertiesFileUtil.getInstance("generator").get("generator.controller.module"); private static String SERVICE_MODULE = PropertiesFileUtil.getInstance("generator").get("generator.service.module"); private static String DAO_MODULE = PropertiesFileUtil.getInstance("generator").get("generator.dao.module"); private static String CONTROLLER_PACKAGE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.controller.package.prefix"); private static String SERVICE_PACKAGE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.service.package.prefix"); private static String DAO_PACKAGE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.dao.package.prefix"); private static String TABLE_PREFIX = PropertiesFileUtil.getInstance("generator").get("generator.table.prefix"); private static String TABLE_LIST = PropertiesFileUtil.getInstance("generator").get("generator.table.list"); private static String DATABASE = PropertiesFileUtil.getInstance("generator").get("generator.database"); private static String JDBC_DRIVER = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.driver"); private static String JDBC_URL = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.url"); private static String JDBC_USERNAME = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.username"); private static String JDBC_PASSWORD = PropertiesFileUtil.getInstance("generator").get("generator.jdbc.password"); /** * 需要insert后返回主键的表配置,key:表名,value:主键名 */
    private static Map<String, String> LAST_INSERT_ID_TABLES = new HashMap<>();/** * 自动代码生成 */
    public static void main(String[] args) throws Exception { MybatisGeneratorUtil.generator(JDBC_DRIVER, JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD, CONTROLLER_MODULE, SERVICE_MODULE, DAO_MODULE, DATABASE, TABLE_PREFIX, TABLE_LIST, CONTROLLER_PACKAGE_PREFIX, SERVICE_PACKAGE_PREFIX, DAO_PACKAGE_PREFIX, LAST_INSERT_ID_TABLES); }

六、自动生成出来的mapper

package edu.nf.project.mapper; import edu.nf.project.model.CityInfo; import edu.nf.project.model.CityInfoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface CityInfoMapper { long countByExample(CityInfoExample example); int deleteByExample(CityInfoExample example); int deleteByPrimaryKey(Integer cityId); int insert(CityInfo record); int insertSelective(CityInfo record); List<CityInfo> selectByExample(CityInfoExample example); CityInfo selectByPrimaryKey(Integer cityId); int updateByExampleSelective(@Param("record") CityInfo record, @Param("example") CityInfoExample example); int updateByExample(@Param("record") CityInfo record, @Param("example") CityInfoExample example); int updateByPrimaryKeySelective(CityInfo record); int updateByPrimaryKey(CityInfo record); }

七、自动生成出来的Model

package edu.nf.project.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import org.springframework.format.annotation.DateTimeFormat; /** * * city_info * * @mbg.generated */
public class CityInfo implements Serializable { /** * 城市编号 * * city_info.city_id */ @ApiModelProperty(value = "城市编号") private Integer cityId; /** * 城市名称 * * city_info.city_name */ @ApiModelProperty(value = "城市名称") private String cityName; /** * 城市编码 * * city_info.city_code */ @ApiModelProperty(value = "城市编码") private String cityCode; /** * 省份 * * city_info.province */ @ApiModelProperty(value = "省份") private String province; private static final long serialVersionUID = 1L; public Integer getCityId() { return cityId; } public void setCityId(Integer cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName == null ? null : cityName.trim(); } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode == null ? null : cityCode.trim(); } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", cityId=").append(cityId); sb.append(", cityName=").append(cityName); sb.append(", cityCode=").append(cityCode); sb.append(", province=").append(province); sb.append("]"); return sb.toString(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CityInfo other = (CityInfo) that; return (this.getCityId() == null ? other.getCityId() == null : this.getCityId().equals(other.getCityId())) && (this.getCityName() == null ? other.getCityName() == null : this.getCityName().equals(other.getCityName())) && (this.getCityCode() == null ? other.getCityCode() == null : this.getCityCode().equals(other.getCityCode())) && (this.getProvince() == null ? other.getProvince() == null : this.getProvince().equals(other.getProvince())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getCityId() == null) ? 0 : getCityId().hashCode()); result = prime * result + ((getCityName() == null) ? 0 : getCityName().hashCode()); result = prime * result + ((getCityCode() == null) ? 0 : getCityCode().hashCode()); result = prime * result + ((getProvince() == null) ? 0 : getProvince().hashCode()); return result; } }

 

package edu.nf.project.model; import java.util.ArrayList; import java.util.List; public class CityInfoExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CityInfoExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCityIdIsNull() { addCriterion("city_id is null"); return (Criteria) this; } public Criteria andCityIdIsNotNull() { addCriterion("city_id is not null"); return (Criteria) this; } public Criteria andCityIdEqualTo(Integer value) { addCriterion("city_id =", value, "cityId"); return (Criteria) this; } public Criteria andCityIdNotEqualTo(Integer value) { addCriterion("city_id <>", value, "cityId"); return (Criteria) this; } public Criteria andCityIdGreaterThan(Integer value) { addCriterion("city_id >", value, "cityId"); return (Criteria) this; } public Criteria andCityIdGreaterThanOrEqualTo(Integer value) { addCriterion("city_id >=", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLessThan(Integer value) { addCriterion("city_id <", value, "cityId"); return (Criteria) this; } public Criteria andCityIdLessThanOrEqualTo(Integer value) { addCriterion("city_id <=", value, "cityId"); return (Criteria) this; } public Criteria andCityIdIn(List<Integer> values) { addCriterion("city_id in", values, "cityId"); return (Criteria) this; } public Criteria andCityIdNotIn(List<Integer> values) { addCriterion("city_id not in", values, "cityId"); return (Criteria) this; } public Criteria andCityIdBetween(Integer value1, Integer value2) { addCriterion("city_id between", value1, value2, "cityId"); return (Criteria) this; } public Criteria andCityIdNotBetween(Integer value1, Integer value2) { addCriterion("city_id not between", value1, value2, "cityId"); return (Criteria) this; } public Criteria andCityNameIsNull() { addCriterion("city_name is null"); return (Criteria) this; } public Criteria andCityNameIsNotNull() { addCriterion("city_name is not null"); return (Criteria) this; } public Criteria andCityNameEqualTo(String value) { addCriterion("city_name =", value, "cityName"); return (Criteria) this; } public Criteria andCityNameNotEqualTo(String value) { addCriterion("city_name <>", value, "cityName"); return (Criteria) this; } public Criteria andCityNameGreaterThan(String value) { addCriterion("city_name >", value, "cityName"); return (Criteria) this; } public Criteria andCityNameGreaterThanOrEqualTo(String value) { addCriterion("city_name >=", value, "cityName"); return (Criteria) this; } public Criteria andCityNameLessThan(String value) { addCriterion("city_name <", value, "cityName"); return (Criteria) this; } public Criteria andCityNameLessThanOrEqualTo(String value) { addCriterion("city_name <=", value, "cityName"); return (Criteria) this; } public Criteria andCityNameLike(String value) { addCriterion("city_name like", value, "cityName"); return (Criteria) this; } public Criteria andCityNameNotLike(String value) { addCriterion("city_name not like", value, "cityName"); return (Criteria) this; } public Criteria andCityNameIn(List<String> values) { addCriterion("city_name in", values, "cityName"); return (Criteria) this; } public Criteria andCityNameNotIn(List<String> values) { addCriterion("city_name not in", values, "cityName"); return (Criteria) this; } public Criteria andCityNameBetween(String value1, String value2) { addCriterion("city_name between", value1, value2, "cityName"); return (Criteria) this; } public Criteria andCityNameNotBetween(String value1, String value2) { addCriterion("city_name not between", value1, value2, "cityName"); return (Criteria) this; } public Criteria andCityCodeIsNull() { addCriterion("city_code is null"); return (Criteria) this; } public Criteria andCityCodeIsNotNull() { addCriterion("city_code is not null"); return (Criteria) this; } public Criteria andCityCodeEqualTo(String value) { addCriterion("city_code =", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeNotEqualTo(String value) { addCriterion("city_code <>", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeGreaterThan(String value) { addCriterion("city_code >", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeGreaterThanOrEqualTo(String value) { addCriterion("city_code >=", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeLessThan(String value) { addCriterion("city_code <", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeLessThanOrEqualTo(String value) { addCriterion("city_code <=", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeLike(String value) { addCriterion("city_code like", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeNotLike(String value) { addCriterion("city_code not like", value, "cityCode"); return (Criteria) this; } public Criteria andCityCodeIn(List<String> values) { addCriterion("city_code in", values, "cityCode"); return (Criteria) this; } public Criteria andCityCodeNotIn(List<String> values) { addCriterion("city_code not in", values, "cityCode"); return (Criteria) this; } public Criteria andCityCodeBetween(String value1, String value2) { addCriterion("city_code between", value1, value2, "cityCode"); return (Criteria) this; } public Criteria andCityCodeNotBetween(String value1, String value2) { addCriterion("city_code not between", value1, value2, "cityCode"); return (Criteria) this; } public Criteria andProvinceIsNull() { addCriterion("province is null"); return (Criteria) this; } public Criteria andProvinceIsNotNull() { addCriterion("province is not null"); return (Criteria) this; } public Criteria andProvinceEqualTo(String value) { addCriterion("province =", value, "province"); return (Criteria) this; } public Criteria andProvinceNotEqualTo(String value) { addCriterion("province <>", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThan(String value) { addCriterion("province >", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThanOrEqualTo(String value) { addCriterion("province >=", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThan(String value) { addCriterion("province <", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThanOrEqualTo(String value) { addCriterion("province <=", value, "province"); return (Criteria) this; } public Criteria andProvinceLike(String value) { addCriterion("province like", value, "province"); return (Criteria) this; } public Criteria andProvinceNotLike(String value) { addCriterion("province not like", value, "province"); return (Criteria) this; } public Criteria andProvinceIn(List<String> values) { addCriterion("province in", values, "province"); return (Criteria) this; } public Criteria andProvinceNotIn(List<String> values) { addCriterion("province not in", values, "province"); return (Criteria) this; } public Criteria andProvinceBetween(String value1, String value2) { addCriterion("province between", value1, value2, "province"); return (Criteria) this; } public Criteria andProvinceNotBetween(String value1, String value2) { addCriterion("province not between", value1, value2, "province"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }

 

七、自动生成XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.nf.project.mapper.CityInfoMapper">
  <resultMap id="BaseResultMap" type="edu.nf.project.model.CityInfo">
    <id column="city_id" jdbcType="INTEGER" property="cityId" />
    <result column="city_name" jdbcType="VARCHAR" property="cityName" />
    <result column="city_code" jdbcType="VARCHAR" property="cityCode" />
    <result column="province" jdbcType="VARCHAR" property="province" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue"> and ${criterion.condition} </when>
                <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when>
                <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when>
                <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue"> and ${criterion.condition} </when>
                <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when>
                <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when>
                <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List"> city_id, city_name, city_code, province </sql>
  <select id="selectByExample" parameterType="edu.nf.project.model.CityInfoExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if>
    <include refid="Base_Column_List" /> from city_info <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null"> order by ${orderByClause} </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from city_info where city_id = #{cityId,jdbcType=INTEGER} </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from city_info where city_id = #{cityId,jdbcType=INTEGER} </delete>
  <delete id="deleteByExample" parameterType="edu.nf.project.model.CityInfoExample"> delete from city_info <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="edu.nf.project.model.CityInfo"> insert into city_info (city_id, city_name, city_code, province) values (#{cityId,jdbcType=INTEGER}, #{cityName,jdbcType=VARCHAR}, #{cityCode,jdbcType=VARCHAR}, #{province,jdbcType=VARCHAR}) </insert>
  <insert id="insertSelective" parameterType="edu.nf.project.model.CityInfo"> insert into city_info <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="cityId != null"> city_id, </if>
      <if test="cityName != null"> city_name, </if>
      <if test="cityCode != null"> city_code, </if>
      <if test="province != null"> province, </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="cityId != null"> #{cityId,jdbcType=INTEGER}, </if>
      <if test="cityName != null"> #{cityName,jdbcType=VARCHAR}, </if>
      <if test="cityCode != null"> #{cityCode,jdbcType=VARCHAR}, </if>
      <if test="province != null"> #{province,jdbcType=VARCHAR}, </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="edu.nf.project.model.CityInfoExample" resultType="java.lang.Long"> select count(*) from city_info <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map"> update city_info <set>
      <if test="record.cityId != null"> city_id = #{record.cityId,jdbcType=INTEGER}, </if>
      <if test="record.cityName != null"> city_name = #{record.cityName,jdbcType=VARCHAR}, </if>
      <if test="record.cityCode != null"> city_code = #{record.cityCode,jdbcType=VARCHAR}, </if>
      <if test="record.province != null"> province = #{record.province,jdbcType=VARCHAR}, </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map"> update city_info set city_id = #{record.cityId,jdbcType=INTEGER}, city_name = #{record.cityName,jdbcType=VARCHAR}, city_code = #{record.cityCode,jdbcType=VARCHAR}, province = #{record.province,jdbcType=VARCHAR} <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="edu.nf.project.model.CityInfo"> update city_info <set>
      <if test="cityName != null"> city_name = #{cityName,jdbcType=VARCHAR}, </if>
      <if test="cityCode != null"> city_code = #{cityCode,jdbcType=VARCHAR}, </if>
      <if test="province != null"> province = #{province,jdbcType=VARCHAR}, </if>
    </set> where city_id = #{cityId,jdbcType=INTEGER} </update>
  <update id="updateByPrimaryKey" parameterType="edu.nf.project.model.CityInfo"> update city_info set city_name = #{cityName,jdbcType=VARCHAR}, city_code = #{cityCode,jdbcType=VARCHAR}, province = #{province,jdbcType=VARCHAR} where city_id = #{cityId,jdbcType=INTEGER} </update>
</mapper>

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

package edu.nf.project.controller; import com.wang.common.base.BaseController; import com.wang.common.model.base.result.DataResult; import com.wang.common.uitl.IdGenerator; import com.wang.common.model.page.PageInfoResult; import com.wang.common.model.page.PageParam; import edu.nf.project.model.CityInfo; import edu.nf.project.model.CityInfoExample; import edu.nf.project.service.CityInfoService; import com.github.pagehelper.PageInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; /** * controller * Created by Administrator on 2019-06-20T11:55:04.44. * * @author Administrator */ @RestController @ResponseBody @RequestMapping(value = "/cityInfo") @Api(value = "控制器", description = "管理") public class CityInfoController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(CityInfoController.class); @Resource private CityInfoService cityInfoService; /** * 列表 * * @param pageParam 分页参数 * @return DataResult */ @GetMapping(value = "/list") @ApiOperation(value = "列表") public PageInfoResult<CityInfo> list(PageParam pageParam) { CityInfoExample cityInfoExample = new CityInfoExample(); List<CityInfo> cityInfoList = cityInfoService.selectByExampleForStartPage(cityInfoExample, pageParam.getPageNum(), pageParam.getPageSize()); long total = cityInfoService.countByExample(cityInfoExample); return new PageInfoResult<>(cityInfoList, total); } /** * 添加 * * @param cityInfo 数据 * @return DataResult */ @PostMapping(value = "/add") @ApiOperation(value = "添加") @RequiresPermissions("cityInfo:add") public DataResult add(@RequestBody CityInfo cityInfo) { cityInfo.setCityId((int)(IdGenerator.getId())); cityInfoService.insertSelective(cityInfo); return new DataResult("success", "保存成功"); } /** * 删除 * * @param id 主键 * @return DataResult */ @GetMapping(value = "/delete") @ApiOperation(value = "删除") @RequiresPermissions("cityInfo:delete") public DataResult delete(Long id) { cityInfoService.deleteByPrimaryKey(id); return new DataResult("success", "删除成功"); } /** * 修改 * * @param cityInfo 数据 * @return DataResult */ @PostMapping(value = "/update") @ApiOperation(value = "修改") @RequiresPermissions("cityInfo:update") public DataResult update(@RequestBody CityInfo cityInfo) { CityInfoExample cityInfoExample = new CityInfoExample(); cityInfoExample.createCriteria().andCityIdEqualTo(cityInfo.getCityId()); cityInfoService.updateByExampleSelective(cityInfo, cityInfoExample); return new DataResult("success", "修改成功"); } /** * 详情 * * @param id 主键 * @return DataResult */ @GetMapping(value = "/detail") @ApiOperation(value = "详情") @RequiresPermissions("cityInfo:detail") public DataResult<CityInfo> detail(Long id) { CityInfo cityInfo = cityInfoService.selectByPrimaryKey(id); return new DataResult<>(cityInfo); } }

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

// api // Created by Administrator on 2019-06-20T10:55:15.236.
import request from '@/utils/requestJson'

// 查找数据
export const listApi = params => { return request.get('/cityInfo/list', { params: params }) } // 添加数据
export const addApi = params => { return request.post('/cityInfo/add', params) } // 修改数据
export const updateApi = params => { return request.post('/cityInfo/update', params) } // 删除数据
export const deleteApi = params => { return request.get('/cityInfo/delete', { params: params }) } // 详细数据
export const detailApi = params => { return request.get('/cityInfo/detail', { params: params }) }
// 编辑 // Created by Administrator on 2019-06-20T10:55:15.236.
<template>
  <el-dialog class="add-permission" title="编辑" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false" :before-close="handleClose">
    <el-form ref="dataForm" size="small" :rules="rules" :model="dataForm" label-width="80px">
    <el-form-item label="" prop="cityId">
      <el-input size="small" v-model="dataForm.cityId" type="text"/>
    </el-form-item>
    <el-form-item label="" prop="cityName">
      <el-input size="small" v-model="dataForm.cityName" type="text"/>
    </el-form-item>
    <el-form-item label="" prop="cityCode">
      <el-input size="small" v-model="dataForm.cityCode" type="text"/>
    </el-form-item>
    <el-form-item label="" prop="province">
      <el-input size="small" v-model="dataForm.province" type="text"/>
    </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="small">取 消</el-button>
      <el-button type="primary" size="small" :loading="loading" @click="saveData">保存</el-button>
    </span>
  </el-dialog>
</template>

<script> import { addApi, detailApi, updateApi } from '@/api/cityInfoApi' class CityInfo { constructor () { this.cityId = null
      this.cityName = null
      this.cityCode = null
      this.province = null } set cityInfo (cityInfo) { this.cityId = cityInfo.cityId this.cityName = cityInfo.cityName this.cityCode = cityInfo.cityCode this.province = cityInfo.province } } export default { data () { return { dialogVisible: false, loading: false, dataForm: new CityInfo(), rules: { systemId: [{ required: true, message: '请选择系统', trigger: 'blur' }], title: [{ required: true, message: '请填写权限名称', trigger: 'blur' }], type: [{ required: true, message: '请选择类型', trigger: 'blur' }], permissionValue: [ { required: true, message: '请填写权限值', trigger: 'blur' } ] } } }, methods: { showDialog (id) { this.dialogVisible = true
        if (id) { detailApi({ id: id }).then(res => { this.dataForm.cityInfo = res.data }) } }, handleClose () { this.dialogVisible = false }, // 保存数据
 saveData () { let refs = this.$refs refs.dataForm.validate(valid => { if (valid) { this.loading = true let api if (this.dataForm.id) { api = updateApi(this.dataForm) } else { api = addApi(this.dataForm) } api.then(res => { this.$message({ type: 'success', message: res.sub_msg }) this.dialogVisible = false
              this.$emit('callback') }).finally(() => { this.loading = false }) } }) } } } </script>
// 列表 // Created by Administrator on 2019-06-20T10:55:15.236.
<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-input placeholder="请输入内容" v-model="listQuery.title" style="width: 200px;" @keyup.enter.native="listSearch" size="small" clearable/>
      <el-button type="primary" icon="el-icon-search" @click="listSearch" size="small">查询</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="addClick" v-if="hasPerm('upms:permManage:addPerm')" style="margin-left:0;" size="small">添加 </el-button>
    </div>
    <!--表格-->
    <div class="table-container">
      <el-table :data="rows" border fit size="small" highlight-current-row style="width: 100%;" v-loading="loading">
        <!-- 需要映射的表 -->
        <el-table-column prop="cityId" label="" align="left" width="150" show-overflow-tooltip/>
        <el-table-column prop="cityName" label="" align="left" width="150" show-overflow-tooltip/>
        <el-table-column prop="cityCode" label="" align="left" width="150" show-overflow-tooltip/>
        <el-table-column prop="province" label="" align="left" width="150" show-overflow-tooltip/>
    
        <el-table-column label="操作" align="left" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button type="primary" @click="editClick(scope.row.CityId)" v-if="hasPerm('upms:permManage:editPerm')" size="mini">编辑 </el-button>
            <el-button type="danger" @click="deleteClick(scope.row.CityId)" v-if="hasPerm('upms:permManage:delPerm')" size="mini">删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageNum" :page-sizes="[10, 20, 30, 40, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--添加、修改组件-->
    <CityInfoEdit ref="cityInfoEditRef" @callback="listSearch"/>
  </div>
</template>
<script> import { deleteApi, listApi } from '@/api/cityInfoApi' import CityInfoEdit from './CityInfoEdit' export default { components: { CityInfoEdit }, data () { return { loading: false, rows: [], listQuery: { systemId: null, title: null, permType: null, pageNum: 1, pageSize: 10 }, total: 0 } }, mounted () { this.listSearch() }, methods: { listSearch () { this.loading = true listApi(this.listQuery).then(res => { this.total = Number(res.total) this.rows = res.list }).finally(() => { this.loading = false }) }, addClick () { this.$refs.cityInfoEditRef.showDialog(this.listQuery.systemId) }, editClick (id) { this.$refs.cityInfoEditRef.showDialog(id) }, deleteClick (id) { this.$confirm('确定删除数据?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { deleteApi({ id: id }).then(res => { this.$message({ type: 'success', message: res.sub_msg }) this.listSearch() }) }) }, // 分页相关
 handleSizeChange (val) { this.listQuery.pageSize = val this.listSearch() }, // 分页相关
 handleCurrentChange (val) { this.listQuery.pageNum = val this.listSearch() } } } </script>

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM