sprignboot3 增删改查

项目初始结构

image

开始

  1. mybatisgenerator 自动生成mapper
    Generator.java
package com.lily.blogs.admin.domain.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class Generator {
	public static void main(String[] args) throws Exception {
		 //MBG 执行过程中的警告信息
		 List<String> warnings = new ArrayList<String>();
		 //当生成的代码重复时,覆盖原代码
		 boolean overwrite = true;
		 //读取我们的 MBG 配置文件
		 InputStream is = Generator.class.getResourceAsStream("/mybatis/generatorConfig.xml");
		 ConfigurationParser cp = new ConfigurationParser(warnings);
		 Configuration config = cp.parseConfiguration(is);
		 is.close();
		 DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		 //创建 MBG
		 MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		 //执行生成代码
		 myBatisGenerator.generate(null);
		 //输出警告信息
		 for (String warning : warnings) {
		 System.out.println(warning);
		 }
		 }
}

CommentGenerator.java

package com.lily.blogs.admin.domain.utils;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;

public class CommentGenerator extends DefaultCommentGenerator {
	private boolean addRemarkComments = false;
	 private static final String EXAMPLE_SUFFIX="Example";
     // private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
     private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.v3.oas.annotations.media.Schema";
	 /**
	 * 设置用户配置的参数
	 */
	 @Override
	 public void addConfigurationProperties(Properties properties) {
	 super.addConfigurationProperties(properties);
	 this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
	 }
	 /**
	 * 给字段添加注释
	 */
	 @Override
	 public void addFieldComment(Field field, IntrospectedTable introspectedTable,
	 IntrospectedColumn introspectedColumn) {
	 String remarks = introspectedColumn.getRemarks();
	 //根据参数和备注信息判断是否添加备注信息
	 if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
	// addFieldJavaDoc(field, remarks);
	 //数据库中特殊字符需要转义
	 if(remarks.contains("\"")){
	 remarks = remarks.replace("\"","'");
	 }
	 //给model的字段添加swagger注解
	 //field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
	 field.addJavaDocLine("@Schema(description = \""+remarks+"\")");
	 }
	 }
	 /**
	 * 给model的字段添加注释
	 */
	 private void addFieldJavaDoc(Field field, String remarks) {
	 //文档注释开始
	 field.addJavaDocLine("/**");
	 //获取数据库字段的备注信息
	 String[] remarkLines = remarks.split(System.getProperty("line.separator"));
	 for(String remarkLine:remarkLines){
	 field.addJavaDocLine(" * "+remarkLine);
	 }
	 addJavadocTag(field, false);
	 field.addJavaDocLine(" */");
	 }
	 @Override
	 public void addJavaFileComment(CompilationUnit compilationUnit) {
	 super.addJavaFileComment(compilationUnit);
	 //只在model中添加swagger注解类的导入
	 if(!compilationUnit.isJavaInterface()&&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)){
		 compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
	 }
	 }
}


  1. 数据库表
    image
  2. 配置文件
    application.properties
server.port = 8081

#spring.datasource.url=jdbc:mysql://localhost:3306/mango?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.profiles.active=dev

application-dev.yaml

server:
  port: 8081
mybatis:
 type-aliases-package: com.lily.blogs.admin.domain
 config-location: classpath:mybatis/mybatis-config.xml
 mapper-locations:
 - classpath:mapper/*.xml
 - classpath*:com/**/mapper/*.xml
spring:
 datasource:
   driver-class-name: com.mysql.cj.jdbc.Driver
   url: jdbc:mysql://localhost:3306/mango?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
   username: root
   password: root
# pagehelper
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  1. 通用配置
    image
    HttpResult.java
package com.lily.blogs.admin.domain.common.http;

public class HttpResult {
	private int code = 200;
	private String msg;
	private Object data;
	
	public static HttpResult error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
	}
	
	public static HttpResult error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static HttpResult error(int code, String msg) {
		HttpResult r = new HttpResult();
		r.setCode(code);
		r.setMsg(msg);
		return r;
	}

	public static HttpResult ok(String msg) {
		HttpResult r = new HttpResult();
		r.setMsg(msg);
		return r;
	}
	
	public static HttpResult ok(Object data) {
		HttpResult r = new HttpResult();
		r.setData(data);
		return r;
	}
	
	public static HttpResult ok() {
		return new HttpResult();
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
}

HttpStatus.java

package com.lily.blogs.admin.domain.common.http;

public interface HttpStatus {
	// --- 1xx Informational ---

    /** {@code 100 Continue} (HTTP/1.1 - RFC 2616) */
    public static final int SC_CONTINUE = 100;
    /** {@code 101 Switching Protocols} (HTTP/1.1 - RFC 2616)*/
    public static final int SC_SWITCHING_PROTOCOLS = 101;
    /** {@code 102 Processing} (WebDAV - RFC 2518) */
    public static final int SC_PROCESSING = 102;

    // --- 2xx Success ---

    /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
    public static final int SC_OK = 200;
    /** {@code 201 Created} (HTTP/1.0 - RFC 1945) */
    public static final int SC_CREATED = 201;
    /** {@code 202 Accepted} (HTTP/1.0 - RFC 1945) */
    public static final int SC_ACCEPTED = 202;
    /** {@code 203 Non Authoritative Information} (HTTP/1.1 - RFC 2616) */
    public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    /** {@code 204 No Content} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NO_CONTENT = 204;
    /** {@code 205 Reset Content} (HTTP/1.1 - RFC 2616) */
    public static final int SC_RESET_CONTENT = 205;
    /** {@code 206 Partial Content} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PARTIAL_CONTENT = 206;
    /**
     * {@code 207 Multi-Status} (WebDAV - RFC 2518)
     * or
     * {@code 207 Partial Update OK} (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
     */
    public static final int SC_MULTI_STATUS = 207;

    // --- 3xx Redirection ---

    /** {@code 300 Mutliple Choices} (HTTP/1.1 - RFC 2616) */
    public static final int SC_MULTIPLE_CHOICES = 300;
    /** {@code 301 Moved Permanently} (HTTP/1.0 - RFC 1945) */
    public static final int SC_MOVED_PERMANENTLY = 301;
    /** {@code 302 Moved Temporarily} (Sometimes {@code Found}) (HTTP/1.0 - RFC 1945) */
    public static final int SC_MOVED_TEMPORARILY = 302;
    /** {@code 303 See Other} (HTTP/1.1 - RFC 2616) */
    public static final int SC_SEE_OTHER = 303;
    /** {@code 304 Not Modified} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_MODIFIED = 304;
    /** {@code 305 Use Proxy} (HTTP/1.1 - RFC 2616) */
    public static final int SC_USE_PROXY = 305;
    /** {@code 307 Temporary Redirect} (HTTP/1.1 - RFC 2616) */
    public static final int SC_TEMPORARY_REDIRECT = 307;

    // --- 4xx Client Error ---

    /** {@code 400 Bad Request} (HTTP/1.1 - RFC 2616) */
    public static final int SC_BAD_REQUEST = 400;
    /** {@code 401 Unauthorized} (HTTP/1.0 - RFC 1945) */
    public static final int SC_UNAUTHORIZED = 401;
    /** {@code 402 Payment Required} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PAYMENT_REQUIRED = 402;
    /** {@code 403 Forbidden} (HTTP/1.0 - RFC 1945) */
    public static final int SC_FORBIDDEN = 403;
    /** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_FOUND = 404;
    /** {@code 405 Method Not Allowed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_METHOD_NOT_ALLOWED = 405;
    /** {@code 406 Not Acceptable} (HTTP/1.1 - RFC 2616) */
    public static final int SC_NOT_ACCEPTABLE = 406;
    /** {@code 407 Proxy Authentication Required} (HTTP/1.1 - RFC 2616)*/
    public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    /** {@code 408 Request Timeout} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_TIMEOUT = 408;
    /** {@code 409 Conflict} (HTTP/1.1 - RFC 2616) */
    public static final int SC_CONFLICT = 409;
    /** {@code 410 Gone} (HTTP/1.1 - RFC 2616) */
    public static final int SC_GONE = 410;
    /** {@code 411 Length Required} (HTTP/1.1 - RFC 2616) */
    public static final int SC_LENGTH_REQUIRED = 411;
    /** {@code 412 Precondition Failed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PRECONDITION_FAILED = 412;
    /** {@code 413 Request Entity Too Large} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_TOO_LONG = 413;
    /** {@code 414 Request-URI Too Long} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_URI_TOO_LONG = 414;
    /** {@code 415 Unsupported Media Type} (HTTP/1.1 - RFC 2616) */
    public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    /** {@code 416 Requested Range Not Satisfiable} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    /** {@code 417 Expectation Failed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_EXPECTATION_FAILED = 417;

    /**
     * Static constant for a 418 error.
     * {@code 418 Unprocessable Entity} (WebDAV drafts?)
     * or {@code 418 Reauthentication Required} (HTTP/1.1 drafts?)
     */
    // not used
    // public static final int SC_UNPROCESSABLE_ENTITY = 418;

    /**
     * Static constant for a 419 error.
     * {@code 419 Insufficient Space on Resource}
     * (WebDAV - draft-ietf-webdav-protocol-05?)
     * or {@code 419 Proxy Reauthentication Required}
     * (HTTP/1.1 drafts?)
     */
    public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
    /**
     * Static constant for a 420 error.
     * {@code 420 Method Failure}
     * (WebDAV - draft-ietf-webdav-protocol-05?)
     */
    public static final int SC_METHOD_FAILURE = 420;
    /** {@code 422 Unprocessable Entity} (WebDAV - RFC 2518) */
    public static final int SC_UNPROCESSABLE_ENTITY = 422;
    /** {@code 423 Locked} (WebDAV - RFC 2518) */
    public static final int SC_LOCKED = 423;
    /** {@code 424 Failed Dependency} (WebDAV - RFC 2518) */
    public static final int SC_FAILED_DEPENDENCY = 424;

    // --- 5xx Server Error ---

    /** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
    public static final int SC_INTERNAL_SERVER_ERROR = 500;
    /** {@code 501 Not Implemented} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_IMPLEMENTED = 501;
    /** {@code 502 Bad Gateway} (HTTP/1.0 - RFC 1945) */
    public static final int SC_BAD_GATEWAY = 502;
    /** {@code 503 Service Unavailable} (HTTP/1.0 - RFC 1945) */
    public static final int SC_SERVICE_UNAVAILABLE = 503;
    /** {@code 504 Gateway Timeout} (HTTP/1.1 - RFC 2616) */
    public static final int SC_GATEWAY_TIMEOUT = 504;
    /** {@code 505 HTTP Version Not Supported} (HTTP/1.1 - RFC 2616) */
    public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

    /** {@code 507 Insufficient Storage} (WebDAV - RFC 2518) */
    public static final int SC_INSUFFICIENT_STORAGE = 507;
}

PageRequest.java

package com.lily.blogs.admin.domain.common.page;

import java.util.HashMap;
import java.util.Map;

/**
 * 分页请求
 * @author Louis
 * @date Jan 12, 2019
 */
public class PageRequest {
	/**
	 * 当前页码
	 */
	private int pageNum = 1;
	/**
	 * 每页数量
	 */
	private int pageSize = 10;
	/**
	 * 查询参数
	 */
	private Map<String, Object> params = new HashMap<>();
	
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public Map<String, Object> getParams() {
		return params;
	}
	public void setParams(Map<String, Object> params) {
		this.params = params;
	}
	public Object getParam(String key) {
		return getParams().get(key);
	}
}

PageResult.java

package com.lily.blogs.admin.domain.common.page;

import java.util.List;

/**
 * 分页返回结果
 * @author Louis
 * @date Jan 12, 2019
 */
public class PageResult {
	/**
	 * 当前页码
	 */
	private int pageNum;
	/**
	 * 每页数量
	 */
	private int pageSize;
	/**
	 * 记录总数
	 */
	private long totalSize;
	/**
	 * 页码总数
	 */
	private int totalPages;
	/**
	 * 分页数据
	 */
	private List<?> content;
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public long getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(long totalSize) {
		this.totalSize = totalSize;
	}
	public int getTotalPages() {
		return totalPages;
	}
	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	public List<?> getContent() {
		return content;
	}
	public void setContent(List<?> content) {
		this.content = content;
	}
}

MybatisPageHelper.java

package com.lily.blogs.admin.domain.common.page;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lily.blogs.admin.domain.common.utils.ReflectionUtils;


/**
 * MyBatis 分页查询助手
 * @author Louis
 * @date Jan 12, 2019
 */
public class MybatisPageHelper {
public static final String findPage = "findPage";
	
	/**
	 * 分页查询, 约定查询方法名为 “findPage” 
	 * @param pageRequest 分页请求
	 * @param mapper Dao对象,MyBatis的 Mapper	
	 * @param args 方法参数
	 * @return
	 */
	public static PageResult findPage(PageRequest pageRequest, Object mapper) {
		return findPage(pageRequest, mapper, findPage);
	}
	
	/**
	 * 调用分页插件进行分页查询
	 * @param pageRequest 分页请求
	 * @param mapper Dao对象,MyBatis的 Mapper	
	 * @param queryMethodName 要分页的查询方法名
	 * @param args 方法参数
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static PageResult findPage(PageRequest pageRequest, Object mapper, String queryMethodName, Object... args) {
		// 设置分页参数
		int pageNum = pageRequest.getPageNum();
		int pageSize = pageRequest.getPageSize();
		PageHelper.startPage(pageNum, pageSize);
		// 利用反射调用查询方法
		Object result = ReflectionUtils.invoke(mapper, queryMethodName, args);
		return getPageResult(pageRequest, new PageInfo((List) result));
	}

	/**
	 * 将分页信息封装到统一的接口
	 * @param pageRequest 
	 * @param page
	 * @return
	 */
	private static PageResult getPageResult(PageRequest pageRequest, PageInfo<?> pageInfo) {
		PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotalSize(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setContent(pageInfo.getList());
		return pageResult;
	}
}

CurdService.java

package com.lily.blogs.admin.domain.common.service;

import java.util.List;

import com.lily.blogs.admin.domain.common.page.PageRequest;
import com.lily.blogs.admin.domain.common.page.PageResult;

public interface CurdService<T> {
	/**
	 * 保存操作
	 * @param record
	 * @return
	 */
	int save(T record);
	
	/**
	 * 删除操作
	 * @param record
	 * @return
	 */
	int delete(T record);
	
	/**
	 * 批量删除操作
	 * @param entities
	 */
	int delete(List<T> records);
	
	/**
	 * 根据ID查询
	 * @param id
	 * @return
	 */
	T findById(Long id);
	
    /**
     * 分页查询
	 * 这里统一封装了分页请求和结果,避免直接引入具体框架的分页对象, 如MyBatis或JPA的分页对象
	 * 从而避免因为替换ORM框架而导致服务层、控制层的分页接口也需要变动的情况,替换ORM框架也不会
	 * 影响服务层以上的分页接口,起到了解耦的作用
	 * @param pageRequest 自定义,统一分页查询请求
	 * @return PageResult 自定义,统一分页查询结果
     */
	PageResult findPage(PageRequest pageRequest);
}

ReflectionUtils.java

package com.lily.blogs.admin.domain.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionUtils {
	/**
	 * 根据方法名调用指定对象的方法
	 * @param object 要调用方法的对象
	 * @param method 要调用的方法名
	 * @param args 参数对象数组
	 * @return
	 */
	public static Object invoke(Object object, String method, Object... args) {
		Object result = null;
		Class<? extends Object> clazz = object.getClass();
		Method queryMethod = getMethod(clazz, method, args);
		if(queryMethod != null) {
			try {
				result = queryMethod.invoke(object, args);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		} else {
			try {
				throw new NoSuchMethodException(clazz.getName() + " 类中没有找到 " + method + " 方法。");
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 根据方法名和参数对象查找方法
	 * @param clazz
	 * @param name
	 * @param args 参数实例数据
	 * @return
	 */
	public static Method getMethod(Class<? extends Object> clazz, String name, Object[] args) {
		Method queryMethod = null;
		Method[] methods = clazz.getMethods();
		for(Method method:methods) {
			if(method.getName().equals(name)) {
				Class<?>[] parameterTypes = method.getParameterTypes();
				if(parameterTypes.length == args.length) {
					boolean isSameMethod = true;
					for(int i=0; i<parameterTypes.length; i++) {
						Object arg = args[i];
						if(arg == null) {
							arg = "";
						}
						if(!parameterTypes[i].equals(args[i].getClass())) {
							isSameMethod = false;
						}
					}
					if(isSameMethod) {
						queryMethod = method;
						break ;
					}
				}
			}
		}
		return queryMethod;
	}
}

SpringDocConfig.java

package com.lily.blogs.admin.domain.config;

import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;

@Configuration
public class SpringDocConfig {
	@Bean
    public OpenAPI mallTinyOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("Mall-Tiny API")
                        .description("SpringDoc API 演示")
                        .version("v1.0.0")
                        .license(new License().name("Apache 2.0").url("https://github.com/macrozheng/mall-learning")))
                .externalDocs(new ExternalDocumentation()
                        .description("SpringBoot实战电商项目mall(50K+Star)全套文档")
                        .url("http://www.macrozheng.com"));
    }
    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group("api")
                .pathsToMatch("/api/**")
                .build();
    }
    @Bean
    public GroupedOpenApi adminApi() {
        return GroupedOpenApi.builder()
                .group("admin")
                .pathsToMatch("/admin/**")
                .build();
    }
}


  1. UsersMapper.java
package com.lily.blogs.admin.domain.mapper;

import com.lily.blogs.admin.domain.model.Users;
import com.lily.blogs.admin.domain.model.UsersExample;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UsersMapper {
    long countByExample(UsersExample example);

    int deleteByExample(UsersExample example);

    int deleteByPrimaryKey(Long id);

    int insert(Users record);

    int insertSelective(Users record);

    List<Users> selectByExample(UsersExample example);

    Users selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") Users record, @Param("example") UsersExample example);

    int updateByExample(@Param("record") Users record, @Param("example") UsersExample example);

    int updateByPrimaryKeySelective(Users record);

    int updateByPrimaryKey(Users record);
    /**
     * 分页查询
     */
    List<Users> findPage();
    /**
     * 根据标签名称查询
     * @param name
     */
    List<Users> findByName(@Param(value="name") String name);
    /**
     * 根据标签名称分页查询
     * @param label
     */
    List<Users> findPageByName(@Param(value="name") String name);
}
  1. UsersService.java
package com.lily.blogs.admin.domain.service;

import java.util.List;

import com.lily.blogs.admin.domain.common.service.CurdService;
import com.lily.blogs.admin.domain.model.Users;

public interface UsersService extends CurdService<Users> {
	/**
	 * 
	 */
	List<Users> findByName(String name);
}

  1. UsersServiceImpl.java
package com.lily.blogs.admin.domain.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lily.blogs.admin.domain.common.page.MybatisPageHelper;
import com.lily.blogs.admin.domain.common.page.PageRequest;
import com.lily.blogs.admin.domain.common.page.PageResult;
import com.lily.blogs.admin.domain.mapper.UsersMapper;
import com.lily.blogs.admin.domain.model.Users;
import com.lily.blogs.admin.domain.service.UsersService;


@Service
public class UsersServiceImpl implements UsersService{
	@Autowired
	private UsersMapper usersMapper;
	@Override
	public int save(Users record) {
		if(record.getId() == null || record.getId() == 0) {
			return usersMapper.insertSelective(record);
		}
		return usersMapper.updateByPrimaryKeySelective(record);
	}
	@Override
	public int delete(Users record) {
		return usersMapper.deleteByPrimaryKey(record.getId());
	}
	@Override
	public int delete(List<Users> records) {
		for(Users record: records) {
			delete(record);
		}
		return 1;
	}
	@Override
	public Users findById(Long id) {
		return usersMapper.selectByPrimaryKey(id);
	}
	@Override
	public PageResult findPage(PageRequest pageRequest) {
		Object name = pageRequest.getParam("name");
		if(name != null) {
			return MybatisPageHelper.findPage(pageRequest, usersMapper, "findPageByName", name);
		}
		return MybatisPageHelper.findPage(pageRequest, usersMapper);
	}
	@Override
	public List<Users> findByName(String name) {
		return usersMapper.findByName(name);
	}
}

  1. UsersController.java
package com.lily.blogs.admin.domain.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lily.blogs.admin.domain.common.http.HttpResult;
import com.lily.blogs.admin.domain.common.page.PageRequest;
import com.lily.blogs.admin.domain.model.Users;
import com.lily.blogs.admin.domain.service.UsersService;

import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "UsersController", description = "users测试")
@RestController
@RequestMapping("/admin/users")
public class UsersController {
	@Autowired
	private UsersService usersService;
	
	@PostMapping(value="/save")
	public HttpResult save(@RequestBody Users record) {
		return HttpResult.ok(usersService.save(record));
	}
	
	@PostMapping(value="/delete")
	public HttpResult delete(@RequestBody List<Users> records) {
		return HttpResult.ok(usersService.delete(records));
	}
	
	@PostMapping(value="/findPage")
	public HttpResult findPage(@RequestBody PageRequest pageRequest) {
		return HttpResult.ok(usersService.findPage(pageRequest));
	}
	
	@PostMapping(value="/findByName")
	public HttpResult findByName(@RequestParam String name) {
		return HttpResult.ok(usersService.findByName(name));
	}
}

  1. 运行Springboot 项目
    image
    访问

http://localhost:8081/admin/hello
image
接口文档 http://localhost:8081/swagger-ui/
image

测试增删改查功能是否正常。

PS:blogs

posted @ 2023-05-15 10:07  子岚天羽卿怜水  阅读(39)  评论(0编辑  收藏  举报