Fork me on github

spring boot构建restful服务

使用spring boot快速构建出restful服务

JPA实现REST

  • 创建spring boot项目,在项目文件pom.xml中添加以下依赖:

         <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</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-rest</artifactId>
         </dependency>
    

添加完数据库相关和spring data jpa以及spring data rest的依赖。

  • 接下来在application.properties中配置相关的数据库连接信息:

         spring.datasource.url=jdbc:mysql://localhost:3306/bus?&useSSL=false&serverTimezone=UTC
         spring.datasource.username=root
         spring.datasource.password=xxxx
         spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
         spring.jpa.show-sql=true
         spring.jpa.hibernate.ddl-auto=none
         server.port=8888
    
  • 创建实体类

          @Entity(name="bus")
         public class Bus{
               @Id
               @GeneratedValue(strategy=GenerationType.IDENTITY)
            private Integer id;
            private Integer busroutes;
            private String return;
            private String deaprture;
              ...setter/getter
            }
    
  • 创建BusRespository

              public interface BusRespository extends JpaRespository<Bus,Integer>{
                     }...JpaRespository中提供了基本的操作数据库的方法
    

这样RESTful服务就构建完成。

  • 测试:可以使用postman进行测试:
    RESTful服务创建成功后,默认的请求路径是实体类名小写再加上后缀。
    尝试测试:
    向数据库添加一条数据,可以发起post请求,请求地址为https://localhost:8888/bus。
    添加成功后,服务端会返回添加的数据基本信息和浏览地址。
posted on 2020-05-15 20:55  markyle  阅读(274)  评论(0编辑  收藏  举报