mybatis-geneator
一、简介
在使用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 = ; 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();
- 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 = ; var34 < var71; ++var34) {
- String tableName = tablePrefixs[var34];
- table = new HashMap();
- 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();
- 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();
- List<Map> keyResult = jdbcUtil.selectByParams(keySql, sqlParams);
- if (!CollectionUtils.isEmpty(keyResult)) {
- Map map = (Map)keyResult.get();
- 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 = ; 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 项目构建,模块化开发)
mybatis-geneator的更多相关文章
- MyBatis Geneator详解<转>
MyBatis Geneator中文文档地址: http://generator.sturgeon.mopaas.com/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看中文版的文档的 ...
- mybatis.generator.configurationFile
mybatis.generator.configurationFile 有一个更好的配置方法,可以不用在generateConfig.xml里面写死驱动的地址:如果你的mybatis连接也是在pom. ...
- Spring boot后台搭建一使用MyBatis集成Mapper和PageHelper
目标: 使用 Spring boot+MyBatis+mysql 集成 Mapper 和 PageHelper,实现基本的增删改查 先建一个基本的 Spring Boot 项目开启 Spring B ...
- MyBatis-Generator最佳实践
引用地址:http://arccode.net/2015/02/07/MyBatis-Generator%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5/ 最近使用MyBati ...
- spring-boot-通用mapper
数据源依赖 druid官方文档:https://github.com/alibaba/druid/wiki/常见问题 <dependency> <groupId>mysql&l ...
- 一步一步教你用IntelliJ IDEA 搭建SSM框架(2)——配置mybatis-geneator
我们要搭建整个SSM框架,所以要继续上篇文章没有完成的工作,下面配置mybatis-geneator,自动生成mybatis代码. 在上篇文章中的pom.xml的配置文件中已经加了mybatis-ge ...
- 【分享】标准springMVC+mybatis项目maven搭建最精简教程
文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...
- Java MyBatis 插入数据库返回主键
最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...
- [原创]mybatis中整合ehcache缓存框架的使用
mybatis整合ehcache缓存框架的使用 mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓 ...
- 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程
本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...
随机推荐
- .net软件日常开发规范-基本标准
一. 基本标准 代码和SQL脚本均不要出现无意义的空格和空行. 所有SQL脚本确保可以重复运行不出错,添加数据的脚本重复运行不会重复添加数据. 能用一行代码或脚本解决的不要写出两行,能用一个方法解决的 ...
- 【程序人生】从湖北省最早的四位java高级工程师之一到出家为僧所引发的深思
从我刚上大学接触程序员这个职业开始,到如今我从事了七年多程序员,这期间我和我的不少小伙伴接受了太多的负面信息,在成长的道路上也真了交了不少的情商税.这些负面信息中,有一件就是我大学班主任 ...
- SpringMVC源码分析6:SpringMVC的视图解析原理
title: SpringMVC源码分析6:SpringMVC的视图解析原理 date: 2018-06-07 11:03:19 tags: - SpringMVC categories: - 后端 ...
- SpringCloud阶段总结
学习时间:8.15 -- 8.29 学习目标:了解SpringCloud常见组件的使用 学习方式: 输入:视频+博客+开源项目代码参考 输出:调试代码+写博客输出 组件列表 服务注册:Eureka 客 ...
- 详解golang net之transport
关于golang http transport的讲解,网上有很多文章读它进行了描述,但很多文章讲的都比较粗,很多代码实现并没有讲清楚.故给出更加详细的实现说明.整体看下来细节实现层面还是比较难懂的. ...
- MSIL实用指南-生成内部类
生成内部类用TypeBuilder的DefineNestedType方法,得到另一个TypeBuilder.内部类的可访问性都是TypeAttributes的“Nested”开头一些成员.实例代码:y ...
- CAS及其ABA问题
CAS.volatile是JUC包实现同步的基础.Synchronized下的偏向锁.轻量级锁的获取.释放,lock机制下锁的获取.释放,获取失败后线程的入队等操作都是CAS操作锁标志位.state. ...
- mysql安装-yum方式
1.环境 查看当前系统环境,使用的是 centos release 6.5 (Final). 2.检查当前系统是否已经安装过mysql rpm -qa | grep mysql 3.如果有,那么删除已 ...
- net core天马行空系列: 泛型仓储和声明式事物实现最优雅的crud操作
系列目录 1.net core天马行空系列:原生DI+AOP实现spring boot注解式编程 哈哈哈哈,大家好,我就是那个高产似母猪的三合,长久以来,我一直在思考,如何才能实现高效而简洁的仓储模式 ...
- HTML(二)属性,标题,段落,文本格式化
HTML属性 HTML属性 HTML 元素可以设置属性 属性可以在元素中添加附加信息 属性一般描述于开始标签 属性总是以名称/值对的形式出现,比如:name="value" 常用属 ...