spring boot jpa

IDEA 创建 Spring Boot项目 选择 JPA 和Mysql驱动

配置 application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/lifa?useUnicode=true&charcaterEncoding=uft8&serverTimezone=UTC
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update  #表示自动创建 entity 对应的数据库表,并且如果有就不在创建了
    show-sql: true # 控制台打印SQL语句

pom中添加

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

目录结构

spring boot jpa

entity

VIP

package top.mgy.lifa.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;

@ApiModel
@Data
@Entity
@Table(name = "t_vip")   //映射到数据库的表名
public class VIP {

    @ApiModelProperty("用户ID")
    @Id     //主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自动增长
    private int id;
    //@Column(name = "name")  如果数据和当前字段不一致则使用 @Column 指定
    @ApiModelProperty("用户名")
    private String name;
    @ApiModelProperty("用户手机号码")
    private String tel;
    @ApiModelProperty("账户余额")
    private BigDecimal balance;
    @ApiModelProperty("卡编号")
    private String cardNo;
    @ApiModelProperty("密码")
    private String pass;
    @ApiModelProperty("注册时间")
    private Date createDate;
}

dao

VIPRepository

package top.mgy.lifa.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import top.mgy.lifa.entity.VIP;

/**
 * JpaRepository<实体类,主键类型>
 */
public interface VIPRepository extends JpaRepository<VIP,Integer> {
}

service

CommonService

package top.mgy.lifa.service;

import java.util.List;

/**
 * 公共 Service
 * @param <T>
 */
public interface CommonService<T> {

    /**
     * 保存
     * @param T
     * @return
     */
     T save(T T);

    /**
     * 根据id删除
     * @param id
     */
     void deleteById(Integer id);

    /**
     * 根据id查找
     * @param id
     * @return
     */
     T findById(Integer id);

    /**
     * 查询所有数据
     * @return
     */
    List<T> findAll();
    
     /**
     * 更新
     * @param t
     * @return
     */
    T update(T t);
}

VipService

package top.mgy.lifa.service;

import top.mgy.lifa.entity.VIP;

public interface VipService extends CommonService<VIP> {

}

VipServiceImpl

package top.mgy.lifa.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.mgy.lifa.dao.VIPRepository;
import top.mgy.lifa.entity.VIP;

import java.util.List;

@Service
public class VipServiceImpl implements VipService {

    @Autowired
    VIPRepository vipRepository;

    @Override
    public VIP save(VIP vip) {
        //更新,添加都是这个方法
        return vipRepository.save(vip);
    }

    @Override
    public void deleteById(Integer id) {
        vipRepository.deleteById(id);
    }

    @Override
    public VIP findById(Integer id) {
        return vipRepository.getOne(id);
    }

    @Override
    public List<VIP> findAll() {
        return vipRepository.findAll();
    }
    
     @Override
    public VIP update(VIP vip) {
        //来自数据库
        VIP entity = vipRepository.findById(vip.getId()).get();

        entity.setTel(vip.getTel());
        entity.setPass(vip.getPass());

        return vipRepository.save(entity);
    }
    
    
}

controller

VIPController

package top.mgy.lifa.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.mgy.lifa.entity.VIP;
import top.mgy.lifa.response.BaseResult;
import top.mgy.lifa.service.VipService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Api(tags = "VIP相关管理相关接口")
@RestController
public class VIPController {

    @Autowired
    VipService vipService;

    @ApiOperation("查询所有VIP用户")
    @GetMapping("/vip/list")
    public List<VIP> list(){
        return vipService.findAll();
    }

    /**
     * 开通会员
     * @param vip
     * @return
     */
    @ApiOperation("添加会员相关接口")
    @ApiImplicitParam(name = "vip",value = "用户信息")
    @PostMapping("vip")
    public VIP list(VIP vip){
        //前端只需要传递 name,pass,tel
        vip.setBalance(new BigDecimal("0"));
        vip.setCardNo("VIP000003");
        vip.setCreateDate(new Date());
        return vipService.save(vip);
    }

    @ApiOperation("根据id查找会员")
    @ApiImplicitParam(name = "id",value = "VIP用户id")
    @GetMapping("/vip/{id}")
    public VIP findById(@PathVariable("id") Integer id){

        try {
            return vipService.findById(id);
        }catch (Exception e){
            return new VIP();
        }

    }
    @ApiOperation("根据id删除VIP用户")
    @ApiImplicitParam(name = "id",value = "VPI用户id")
    @DeleteMapping("/vip/{id}")
    public BaseResult delete(@PathVariable("id") Integer id){
        try {
            vipService.deleteById(id);
            return new BaseResult(true,"删除成功");
        }catch (Exception e){
            return new BaseResult(false,"删除失败");
        }

    }

    @ApiOperation("修改VIP用户信息(只允许修改密码和手机号)")
    @ApiImplicitParam(name = "vip",value = "用户信息")
    @PutMapping("/vip")
    public VIP update(VIP vip){
        //只允许修改密码和手机号
        return vipService.update(vip);
    }
}


数据库插入数据

spring boot jpa

可以看到 返回了 json数据

spring boot jpa

请求方式

请求方式 请求路径 说明
GET http://localhost:8080/vip/list 查询全部
POST http://localhost:8080/vip 保存数据(传递name,pass,tel)
GET http://localhost:8080/vip/{id} 根据id查询
DELETE http://localhost:8080/vip/{id} 根据id删除
PUT http://localhost:8080/vip 修改/更新数据(传递 id,pass,tel)

整合swagger2

  • 导入依赖
 <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
  • 创建包configuration
  • SwaggerConfig
package top.mgy.lifa.configuration;

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.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 createRestApi(){

        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.mgy.lifa"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                .title("Spring Boot 整合 RestApi测试")
                .description("详细信息略")
                .version("0.1")
                .contact(new Contact("Mgy","https://www.maguangyi.top","960340139@qq.com"))
                .build());
    }
}

spring boot jpa

上一篇:如何创建自已的电子邮箱?国际商务邮箱那个好?


下一篇:vip文章测试