springboot整合swagger UI 、spring-data-JPA

本博客为个人所写,有不对地方请大家指正!

1.首先目录结构

springboot整合swagger UI 、spring-data-JPA_第1张图片

2.pom.xml



	4.0.0

	cn.zw
	demo1
	0.0.1-SNAPSHOT
	jar

	demo1
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.4.3.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
		2.5.0
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
		
			mysql
			mysql-connector-java
			5.1.29
		

		
			org.springframework.boot
			spring-boot-starter-tomcat
			
		

		
			org.springframework.boot
			spring-boot-starter-data-jpa
		

		
			io.springfox
			springfox-swagger2
			${springfox-swagger2.version}
		

		
			io.springfox
			springfox-swagger-ui
			${springfox-swagger2.version}
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	




3.配置swagger

@Configuration
@EnableSwagger2
@ComponentScan("cn.zw.web")
public class Swagger2 {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.zw.web"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfoBuilder().title("Spring Boot 整合 swagger ui")
                .description("Spring Boot 整合 swagger ui 和spring-data-JPA")
                .license("MIT")
                .licenseUrl("http://opensource.org/licenses/MIT")
                .contact(new Contact("李俊樊", "http://blog.csdn.net/lijunfan_rh/article", "[email protected]"))
                .version("1.0")
                .build();

        return apiInfo;
    }

}


4.配置application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
#spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,主要作用是:自动创建、更新、验证数据库表结构,该参数的几种配置如下:

#create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
#create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
#update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
#validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

5.实体类user

@Entity(name = "User")
public class User {

    @Id
    @GeneratedValue
    private Integer id;

    @Column(nullable = false)
    private String name;
    @Column(nullable = false)
    private String age;

    public User() {
    }

    public User(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}



6.dao层 userRepository

public interface UserRepository extends JpaRepository {
    

}





7.启动类Demo1Application

@SpringBootApplication
public class Demo1Application {

	public static void main(String[] args) {
		SpringApplication.run(Demo1Application.class, args);
	}
}


8.WebController

import cn.zw.dao.UserRepository;
import cn.zw.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping(value="/users")
public class WebController {
    @Resource
    UserRepository userRepository;
    
    /*其中@ApiOperation和@ApiParam为添加的API相关注解,各参数说明如下:
    @ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码;
    @ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”
    */
    @ApiOperation(value="获取用户列表", notes="你好我也好!")
    @RequestMapping(value={""}, method= RequestMethod.GET)
    public List getUserList() {
        List r = new ArrayList(userRepository.findAll());
        return r;
    }



    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        userRepository.save(user);
        return "success "+user.toString();
    }



    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String",paramType = "path")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable String id) {
        return  userRepository.findOne(Integer.valueOf(id));
    }



    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    })
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable String id, @RequestBody User user) {
        User u = userRepository.findOne(Integer.valueOf(id));
        u.setName(user.getName());
        u.setAge(user.getAge());
        userRepository.saveAndFlush(u);
        return "success  "+u.toString();
    }



    @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String",paramType = "path")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable String id) {
        userRepository.delete(Integer.valueOf(id));
        return "success";
    }

}



9.访问localhost:8080/swagger-ui.html

springboot整合swagger UI 、spring-data-JPA_第2张图片

springboot整合swagger UI 、spring-data-JPA_第3张图片

springboot整合swagger UI 、spring-data-JPA_第4张图片



  •  That's all



你可能感兴趣的:(spring,boot,spring)