springboot + jpa + redis + hibernate validator + 后台抽象

版权声明:本文为博主原创文章,未经博主允许不得转载。

本文目的:

1.想写一套自己的后台框架

2.激励自己学习的兴趣

那么代码开始

一,pom 文件

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dencycheng</groupId>
    <artifactId>admin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>admin</name>
    <description>后台管理</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 返回Json -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

二,配置文件 application.yml

#server
server:
   port:8080
   server.tomcat.uri-encoding:UTF-8
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpatest?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate.format_sql: true
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: UTC
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 1000

三,公共dao层

package com.dencycheng.framework.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

/**
 * @author  DencyCheng
 * @param <T>
 */
@NoRepositoryBean
public interface BaseDao<T> extends JpaRepository<T, Integer>, JpaSpecificationExecutor<T> {
     T findOneById(Integer id);
}

四,公共service层

package com.dencycheng.framework.service;

import com.dencycheng.framework.common.ResponseResult;
import com.dencycheng.framework.dao.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import java.util.List;
import javax.persistence.criteria.*;

/**
 * Created by Dency Cheng on 2018/8/7/007.
 */
@EnableCaching
public class BaseService<T> {

    @Autowired
    BaseDao<T> baseDao;

    
    public T save(T t) {
        return baseDao.save(t);
    }

    public void deleteById(Integer id) {
        baseDao.deleteById(id);
    }

    public void batchDelete(List deleteList) {
        baseDao.deleteAll(deleteList);
    }

    public T findOneById(Integer id) {
        return baseDao.findOneById(id);
    }

    @Cacheable(value = "searchList",key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#root.args")
    public ResponseResult searchList(Integer num, Integer size, String name) {

        int newNum = StringUtils.isEmpty(num) ? 0 : num;
        int newSize = StringUtils.isEmpty(size) ? 10 : size;
        Sort sort = new Sort(Sort.Direction.DESC, "createDt");
        Pageable pageable = new PageRequest(newNum, newSize, sort);
        Page<T> pages = null;
        if (StringUtils.isEmpty(name)) {
            pages = baseDao.findAll(pageable);
        } else {
            Specification<T> specifications = new Specification<T>() {
                @Override
                public Predicate toPredicate(Root root,
                                             CriteriaQuery query,
                                             CriteriaBuilder cb) {
                    Path path = root.get("name");
                    return cb.like(path, name);
                }
            };
        }

        if (pages.getContent().size() == 0) {
            return ResponseResult.noResult();
        } else {
            return ResponseResult.isScuess(pages);
        }


    }
  
}

五,返回类 

ResponseResult 

package com.dencycheng.framework.common;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.Serializable;

/**
 * 统一返回
 * @author DencyCheng
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult implements Serializable{
    private Integer code;
    private String state;
    private Object data;

    /**
     * 正常返回结果
     * @param object
     * @return
     */
    public static ResponseResult isScuess(Object object){
        return new ResponseResult(Code.SUCCESS.getCode(), State.SCUUESS.name(),object);
    }

    /**
     * 正常返回结果
     * @return
     */
    public static ResponseResult isScuess(){
        return new ResponseResult(Code.SUCCESS.getCode(), State.SCUUESS.name(),"操作成功");
    }

    /**
     * 查询无结果
     * @return
     */
    public static ResponseResult noResult(){
        return new ResponseResult(Code.NORESULT.getCode(), State.SCUUESS.name(),"无数据");
    }

    /**
     * 返回错误信息
     * @param object
     * @return
     */
    public static ResponseResult isError(Object object){
        return new ResponseResult(Code.ERROR.getCode(), State.ERROR.name(),object);
    }

    /**
     * 参数错误
     * @param object
     * @return
     */
    public static ResponseResult isParmError(Object object){
        return new ResponseResult(Code.PARMERROR.getCode(), State.ERROR.name(),object);
    }

    /**
     * 参数错误
     * @return
     */
    public static ResponseResult isParmError(){
        return new ResponseResult(Code.PARMERROR.getCode(), State.ERROR.name(),"缺少参数");
    }


    public ResponseResult(Integer code, String state, Object data) {
        this.code = code;
        this.state = state;
        this.data = data;
    }

    public ResponseResult(Integer code, String state) {
        this.code = code;
        this.state = state;
    }

    public Integer getCode() {
        return code;
    }

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

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
Code
package com.dencycheng.framework.common;

/**
 * 返回结果CODE
 */
public enum Code {
    SUCCESS("成功",200),
    NORESULT("没有检索到数据",201),
    PARMERROR("参数错误",202),
    ERROR("失败",202),
    NOPERMISSION ("无权限访问",40001);

    private String desc;
    private int code;

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public int getCode() {
        return code;
    }

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

    Code(String desc, int code) {
        this.desc = desc;
        this.code = code;
    }
}

State

package com.dencycheng.framework.common;

/**
 * 请求状态
 */
public enum State {
    SCUUESS,
    ERROR;
}

六,user类

package com.dencycheng.admin.model;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;

/**
 * 用户实体类
 * @author DencyCheng
 */
@Table(name = "t_user")
@Entity
public class User  implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;

    @NotNull(message = "{CMM_E0008}年龄")
    @Max(value = 100, message = "年龄{CMM_E0017}100")
    @Min(value = 0, message = "{CMM_E0016}0")
    private Integer age;

    @NotNull(message = "{CMM_E0008}姓名")
    @Size(max = 9, message = "姓名{CMM_E0012}")
    private String name;

    private Date createDt;

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreateDt() {
        return createDt;
    }

    public void setCreateDt(Date createDt) {
        this.createDt = createDt;
    }
}

七,userDao

package com.dencycheng.admin.dao;

import com.dencycheng.admin.model.User;
import com.dencycheng.framework.dao.BaseDao;

public interface UserDao extends BaseDao<User> {

}

八,userService

package com.dencycheng.admin.service;


import com.dencycheng.admin.dao.UserDao;
import com.dencycheng.admin.model.User;
import com.dencycheng.framework.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author DencyCheng
 */
@Service
public class UserService extends BaseService<User> {
    @Autowired
    UserDao userDao;
}

九,userController

package com.dencycheng.admin.controller;

import com.dencycheng.admin.model.User;
import com.dencycheng.admin.service.UserService;
import com.dencycheng.framework.common.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 搜索列表
     * @param num
     * @param size
     * @param name
     * @return
     */
    @PostMapping("list/{num}/{size}")
    private ResponseResult searchList(@PathVariable Integer num,@PathVariable Integer size, String name){
        return userService.searchList(num,size,name);
    }


    /**
     * 查询单个用户
     *
     * @param id
     * @return
     */
    @PostMapping("/findOneById/{id}")
    private ResponseResult findOneById(@PathVariable Integer id) {
        if (id == null) {
            return ResponseResult.isParmError();
        }
        User user = userService.findOneById(id);
        if (user == null) {
            return ResponseResult.noResult();
        } else {
            return ResponseResult.isScuess(user);
        }
    }

    /**
     * 保存,更新
     *
     * @return
     */
    @PostMapping("/save")
    private ResponseResult save(@Valid User user, BindingResult result) {
        Map<String, String> errorsMap = new HashMap<String, String>();
        // 普通校验
        if (result.hasErrors()) {
            result.getFieldErrors().forEach(p -> {
                errorsMap.put(p.getField(), p.getDefaultMessage());
            });
        }

        if (!errorsMap.isEmpty()) {
            return ResponseResult.isParmError(errorsMap);
        }

        //业务校验
        
        return ResponseResult.isScuess(userService.save(user));
    }

    /**
     * 删除
     *
     * @return
     */
    @PostMapping("/delete/{id}")
    private ResponseResult delete(@PathVariable Integer id) {

        if (id == null) {
            return ResponseResult.isParmError();
        }
        userService.deleteById(id);
        return ResponseResult.isScuess();
    }


}

注:项目还在改善中,现在不是很完美

项目码云地址:https://gitee.com/DencyCheng/admin-api

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券