springboot+jpa+vue+swagger测试小demo

1.第一步创建springboot项目(须勾选以下)
springboot+jpa+vue+swagger测试小demo_第1张图片
2.在pom.xml中添加添加对swagger的依赖


            io.springfox
            springfox-swagger2
            2.7.0
 
 
            io.springfox
            springfox-swagger-ui
            2.7.0
  

3.yml文件配置(注意修改数据库)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springbootvue?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
    password: root
    username: root
  jpa:
    database: mysql
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
    show-sql: true

4.进行如下分层
springboot+jpa+vue+swagger测试小demo_第2张图片
5.写实体类(以下提供两种:1.多表查询,2.单表查询)

//多表  Student表
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    @Column
    private String sex;

    //多表查询中的外键
    @Column(name = "gradeId",insertable = false,updatable = false)
    private Integer gradeId;

    //多表查询多对一建立关系
    @ManyToOne
    @JoinColumn(name = "gradeId",referencedColumnName = "id")
    private Grade grade;

//Grade表
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;
//单表   Student表
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String sex;

    private Integer gradeId;

6.写dao层代码继承JpaRepository即可,如:

public interface StudentDao extends JpaRepository {

//可以通过注解自己写sql语句,如果jpa提供的方法够用就不需要写
@Query(value = "select * from Student where name like concat('%',?,'%') ",nativeQuery = true)
List slist();
}

7.写service层
7.1接口(内包含分页、增删改,其中增改同用一个方法:save(Student student))

public interface StudentService {

    Page findByPage(Integer page, Integer size);

    Student save(Student student);

    void delete(Integer id);
}

7.2实现类实现接口方法

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentDao studentDao;

    @Override
    public Page findByPage(Integer page, Integer size) {
        PageRequest of = PageRequest.of(page, size);
        Page pages = studentDao.findAll(of);
        return pages;
    }

    @Override
    public Student save(Student student) {
        System.out.println(student.getSex());
        return studentDao.save(student);
    }

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

8.写controller层(controller中所返回数据皆为JSON格式,以实现前后端分离)

@RestController
@RequestMapping("/student")
@Api(value = "swagger ui 注释 api 级别")
public class StudentController {

    @Resource
    private StudentService studentService;

    @GetMapping("/findByPage")
    @ApiOperation(value = "查询学生",notes = "分页查询学生信息")
    public Page findByPage(Integer page, Integer size){
        Page students = studentService.findByPage(page, size);
        return students;
    }

    @PostMapping("/save")
    @ApiOperation(value = "操作学生",notes = "新增或修改一个学生信息")
    public Student save(@RequestBody Student student){
        return studentService.save(student);
    }

    @DeleteMapping("/del")
    @ApiOperation(value = "删除学生",notes = "删除一个学生信息")
    public int del(Integer id){
        try {
            studentService.delete(id);
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }

    }
}

9.不知道大家还记得我们的config包吗,它有什么用呢,我们接下来就完善它
以下两个类直接放进去即可

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                											`在这里插入代码片`//此处记得修改为直接controller包的路径
                .apis(RequestHandlerSelectors.basePackage("com.lzy.springbootvueswagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2实现前后端分离开发")
                .description("此项目只是练习如何实现前后端分离开发的小Demo")
                .termsOfServiceUrl("https://blog.csdn.net/lzy_yuan")
                .contact("刘仲远")
                .version("1.0")
                .build();
    }
}

@Configuration
public class WebConfig implements WebMvcConfigurer {

    //跨域配置
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }
}

以上,我们的后台算是完成,运行起来后去浏览器访问 http://localhost:8080/swagger-ui.html
springboot+jpa+vue+swagger测试小demo_第3张图片
可点击student-controller查看并检验功能
springboot+jpa+vue+swagger测试小demo_第4张图片
springboot+jpa+vue+swagger测试小demo_第5张图片
springboot+jpa+vue+swagger测试小demo_第6张图片
好了,大家可以测试,后台到此结束
接下来我们去写前端页面



	
		
		
		
		
		
		
	
	
		
编号 姓名 性别 年级 操作

大发福利,全给大家,反正只有一个html页面
所以,告辞

你可能感兴趣的:(新人贴)