1.pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lz</groupId>
<artifactId>hehuorenservice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hehuorenservice</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除掉logging,不使用logback,改用log4j2 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!--引入swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<!-- 验证参数 -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- validation-api 需要依赖hibernate validator-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<!--引入面向切面依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!--引入热启动依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.application.yml
server:
port: 8888
spring:
datasource:
druid:
# 数据库访问配置, 使用druid数据源
username: root
password: 123456
url: jdbc:mysql://localhost:3306/homedecoration?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
# 实体类的路径
type-aliases-package: com.lz.homedecoration.entity
#映射的mysql的mapper的xml文件目录
mapper-locations: classpath:/mapper/*.xml
3.目录结构如下:
3.建表:
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
4.目录代码如下:
4.1 自定义异常类:
package com.lz.homedecoration.common.bean;
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
4.2 自定义分页实体类:
package com.lz.homedecoration.common.bean;
import java.util.List;
public class PageResult<T> {
private List<T> list;
private long count;
public PageResult(List<T> list, long count) {
this.list = list;
this.count = count;
}
public PageResult() {
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
4.3 swagger配置类:
package com.lz.homedecoration.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf())
.select()
.apis(RequestHandlerSelectors.basePackage("com.lz.homedecoration"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInf() {
return new ApiInfoBuilder()
.title("系统API文档")
.contact(new Contact("hong", "/", "10000@qq.com"))
.version("1.0")
.build();
}
}
4.4 controller的基类:
package com.lz.homedecoration.common.controller;
import com.lz.homedecoration.common.bean.PageResult;
import com.lz.homedecoration.common.request.PageReq;
import com.lz.homedecoration.common.response.ResultRes;
import com.lz.homedecoration.entity.User;
import org.springframework.web.bind.annotation.*;
import java.util.List;
public abstract class BaseController<T> {
@GetMapping("/list")
public abstract ResultRes list();
@GetMapping("/get/{id}")
public abstract ResultRes get(@PathVariable Long id);
@PostMapping("/add")
public abstract ResultRes add(@RequestBody User user);
@RequestMapping(value = "/update",method = RequestMethod.PATCH)
public abstract ResultRes update(@RequestBody User user);
@RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
public abstract ResultRes delete(@PathVariable Long id) throws Exception;
@PostMapping("/pageList")
public abstract ResultRes pageList(@RequestBody PageReq pageReq);
}
4.5 dao的基类:
package com.lz.homedecoration.common.dao;
import com.lz.homedecoration.common.request.PageReq;
import java.io.Serializable;
import java.util.List;
public interface BaseDao<T,PK extends Serializable> {
List<T> list();
T get(PK id);
int add(T t);
int delete(PK id);
int update(T t);
List<T> page(PageReq<T> t);
long count(PageReq<T> t);
}
4.6 ControllerAdvice异常拦截类:
package com.lz.homedecoration.common.exception;
import com.lz.homedecoration.common.response.ResultRes;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResultRes exceptionHandle(Exception e){
return ResultRes.fail(e.getMessage());
}
}
4.7 分页入参类封装:
package com.lz.homedecoration.common.request;
public class PageReq<T> {
private T parameter;
private long page;
private long pageSize;
private long startRow;
public T getParameter() {
return parameter;
}
public void setParameter(T parameter) {
this.parameter = parameter;
}
public long getPage() {
if(page<=0){
this.setPage(1);
}
return page;
}
public void setPage(long page) {
this.page = page;
}
public long getPageSize() {
if(pageSize==0){
this.setPageSize(10);
}
return pageSize;
}
public void setPageSize(long pageSize) {
this.pageSize = pageSize;
}
public long getStartRow() {
return (this.page-1)*pageSize;
}
public void setStartRow(long startRow) {
this.startRow = startRow;
}
}
4.8 接口响应结果类:
package com.lz.homedecoration.common.response;
import lombok.Data;
@Data
public class ResultRes {
private Object data;
private String message;
private int code;
public ResultRes(Object data, String message, int code) {
this.data = data;
this.message = message;
this.code = code;
}
public static ResultRes success(Object data, String message, int code){
ResultRes resultRes = new ResultRes(data,message,code);
return resultRes;
}
public static ResultRes success(Object data,String message){
ResultRes resultRes = new ResultRes(data,message,1);
return resultRes;
}
public static ResultRes success(Object data){
ResultRes resultRes = new ResultRes(data,"操作成功",1);
return resultRes;
}
public static ResultRes success(){
ResultRes resultRes = new ResultRes(null,"操作成功",1);
return resultRes;
}
public static ResultRes fail(Object data,String message, int code){
ResultRes resultRes = new ResultRes(data,message,code);
return resultRes;
}
public static ResultRes fail(Object data,String message){
ResultRes resultRes = new ResultRes(data,message,0);
return resultRes;
}
public static ResultRes fail(Object data){
ResultRes resultRes = new ResultRes(data,"操作失败",0);
return resultRes;
}
public static ResultRes fail(){
ResultRes resultRes = new ResultRes(null,"操作失败",0);
return resultRes;
}
}
4.9 service基类:
package com.lz.homedecoration.common.service;
import com.lz.homedecoration.common.bean.PageResult;
import com.lz.homedecoration.common.request.PageReq;
import java.io.Serializable;
import java.util.List;
public interface BaseService<T,PK extends Serializable> {
List<T> list();
T get(PK id);
int add(T t);
int delete(PK id);
int update(T t);
PageResult<T> pageList(PageReq<T> pageReq);
}
4.10 serviceImpl基类封装:
package com.lz.homedecoration.common.service.impl;
import com.lz.homedecoration.common.bean.PageResult;
import com.lz.homedecoration.common.dao.BaseDao;
import com.lz.homedecoration.common.request.PageReq;
import com.lz.homedecoration.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
public class BaseServiceImpl<T, PK extends Serializable> implements BaseService<T, PK> {
@Autowired
BaseDao<T, PK> baseDao;
public List<T> list() { return baseDao.list(); }
@Override
public T get(PK id) {
return (T) baseDao.get(id);
}
@Override
public int add(T t) {
return baseDao.add(t);
}
@Override
public int delete(PK id) {
return baseDao.delete(id);
}
@Override
public int update(T t) {
return baseDao.update(t);
}
@Override
public PageResult<T> pageList(PageReq<T> pageReq) {
PageResult<T> pageResult = new PageResult<T>();
pageResult.setList(baseDao.page(pageReq));
long count = baseDao.count(pageReq);
pageResult.setCount(count);
return pageResult;
}
}
4.11 日志打印工具类:
package com.lz.homedecoration.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommonLogUtil {
public static Logger logger = LoggerFactory.getLogger(CommonLogUtil.class);
}
4.12 用户的controller层,基础controller的基类并实现实基类的实现。
package com.lz.homedecoration.controller;
import com.lz.homedecoration.common.bean.PageResult;
import com.lz.homedecoration.common.controller.BaseController;
import com.lz.homedecoration.common.request.PageReq;
import com.lz.homedecoration.common.response.ResultRes;
import com.lz.homedecoration.entity.User;
import com.lz.homedecoration.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lz.homedecoration.common.util.CommonLogUtil;
@RestController
@RequestMapping("/user")
@Api(value = "用户")
public class UserController extends BaseController<User> {
@Autowired
UserService userService;
@ApiOperation(value = "获取用户列表", notes = "获取用户列表")
@Override
public ResultRes list() {
return ResultRes.success(userService.list());
}
@ApiOperation(value = "获取用户信息", notes = "根据用户id获取用户信息")
@ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path")
@Override
public ResultRes get(@PathVariable Long id) {
User user = userService.get(id);
return ResultRes.success(user);
}
@Override
public ResultRes add(@RequestBody User user) {
userService.add(user);
return ResultRes.success();
}
@Override
public ResultRes update(@RequestBody User user) {
userService.update(user);
return ResultRes.success();
}
@Override
public ResultRes delete(@PathVariable Long id) {
int count = userService.delete(id);
if(count !=0){
return ResultRes.success();
}else {
CommonLogUtil.logger.info("---------没有相关id: "+id+"的数据-------------");
throw new RuntimeException("没有相关id: "+id+"的数据");
}
}
@Override
public ResultRes pageList(@RequestBody PageReq pageReq) {
PageResult<User> pageResult = userService.pageList(pageReq);
return ResultRes.success(pageResult);
}
}
4.13 用户的dao类继承dao的基类:
package com.lz.homedecoration.dao;
import com.lz.homedecoration.common.dao.BaseDao;
import com.lz.homedecoration.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao extends BaseDao<User,Long> {
}
4.14 用户实体类:
package com.lz.homedecoration.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
int id;
String name;
String password;
String createTime;
String updateTime;
}
4.15 用户的service层继承service的基类:
package com.lz.homedecoration.service;
import com.lz.homedecoration.common.service.BaseService;
import com.lz.homedecoration.entity.User;
public interface UserService extends BaseService<User,Long> {
}
4.16 用户的实现类serviceImpl继承对应的serviceImpl基类的方法:
package com.lz.homedecoration.service.impl;
import com.lz.homedecoration.common.service.impl.BaseServiceImpl;
import com.lz.homedecoration.entity.User;
import com.lz.homedecoration.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends BaseServiceImpl<User,Long> implements UserService {
}
4.17 springboot的应用主类:
package com.lz.homedecoration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** @author Administrator */
@SpringBootApplication
@MapperScan(basePackages = {"com.lz.homedecoration.dao"}) // 配置dao类的扫码路径
public class HomeDecorationApplication {
public static void main(String[] args) {
SpringApplication.run(HomeDecorationApplication.class, args);
}
}
4.18 user的mapper.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="com.lz.homedecoration.dao.UserDao">
<resultMap id="userMap" type="com.lz.homedecoration.entity.User">
<result property="id" column="id" jdbcType="INTEGER"></result>
<result property="name" column="name" jdbcType="VARCHAR"></result>
<result property="password" column="password" jdbcType="VARCHAR"></result>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"></result>
<result property="updateTime" column="update_time" jdbcType="TIMESTAMP"></result>
</resultMap>
<select id="list" resultMap="userMap">
select * from user
</select>
<select id="get" resultMap="userMap">
select * from user where id=#{id}
</select>
<select id="page" resultMap="userMap">
select * from user
<trim prefix="where" suffixOverrides="and">
<include refid="listWhere"></include>
</trim>
<if test="page!=null and pageSize!=null">
<![CDATA[LIMIT #{startRow},#{pageSize} ]]>
</if>
</select>
<select id="count" resultType="Long">
select count(1) from user
<trim prefix="where" suffixOverrides="and">
<include refid="listWhere"></include>
</trim>
</select>
<insert id="add" parameterType="com.lz.homedecoration.entity.User">
insert into user (
<trim suffixOverrides=",">
<if test="name !=null">name,</if>
<if test="password !=null">password,</if>
<if test="createTime !=null">createTime,</if>
<if test="updateTime !=null">updateTime,</if>
</trim>
) values (
<trim prefixOverrides="," suffixOverrides=",">
<if test="name !=null">#{name,jdbcType = VARCHAR},</if>
<if test="password !=null">#{password,jdbcType = VARCHAR},</if>
<if test="createTime !=null">#{createTime,jdbcType = TIMESTAMP},</if>
<if test="updateTime !=null">#{updateTime,jdbcType = TIMESTAMP},</if>
</trim>
)
</insert>
<update id="update" parameterType="com.lz.homedecoration.entity.User">
update user
<trim prefix="set" suffixOverrides=",">
<if test="name !=null">name = #{name,jdbcType = VARCHAR},</if>
<if test="password !=null">password = #{password,jdbcType = VARCHAR},</if>
<if test="createTime !=null">createTime = #{createTime,jdbcType = TIMESTAMP},</if>
<if test="updateTime !=null">updateTime = #{updateTime,jdbcType = TIMESTAMP},</if>
</trim>
<where>
id=#{id}
</where>
</update>
<delete id="delete">
delete from user where id= #{id}
</delete>
<sql id="listWhere">
<if test="parameter !=null">
<if test="parameter.name !=null">name = #{parameter.name,jdbcType = VARCHAR} and</if>
<if test="parameter.password !=null">password = #{parameter.password,jdbcType = VARCHAR} and</if>
<if test="parameter.createTime !=null">createTime = #{parameter.createTime,jdbcType = TIMESTAMP} and</if>
<if test="parameter.updateTime !=null">updateTime = #{parameter.updateTime,jdbcType = TIMESTAMP} and</if>
</if>
</sql>
</mapper>
源码:
https://gitee.com/hyhshy/base.git