springboot使用REST访问JPA数据

资料来源:官方指南https://spring.io/guides/gs/accessing-data-rest/

一、创建一个maven工程spring-boot-hello,pom.xml文件中引入项目依赖

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Accessing JPA Data with REST -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <!-- junit5运行所需jar包 -->
        <dependency>
		    <groupId>org.junit.jupiter</groupId>
		    <artifactId>junit-jupiter-engine</artifactId>
		    <scope>test</scope>
		</dependency>
		<dependency>
		    <groupId>org.junit.platform</groupId>
		    <artifactId>junit-platform-runner</artifactId>
		    <scope>test</scope>
		</dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>


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

二、创建实体类Person.java

package com.szcatic.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	private String firstName;
	private String lastName;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

 三、创建接口PersonRepository.java

package com.szcatic.repositories;

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.szcatic.entity.Person;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

	List<Person> findByLastName(@Param("name") String name);

}

四、创建引导类Application.java

package com.szcatic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

五、启动引导类主程序


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-04-18 20:36:52.222  INFO 8876 --- [           main] com.szcatic.Application                  : Starting Application on zsx with PID 8876 (F:\workspace4.11\spring-boot-hello\target\classes started by admin in F:\workspace4.11\spring-boot-hello)
2019-04-18 20:36:52.225  INFO 8876 --- [           main] com.szcatic.Application                  : No active profile set, falling back to default profiles: default
2019-04-18 20:36:53.146  INFO 8876 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-04-18 20:36:53.212  INFO 8876 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 58ms. Found 1 repository interfaces.
2019-04-18 20:36:53.569  INFO 8876 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$a34b7b4d] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-18 20:36:53.591  INFO 8876 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.hateoas.config.HateoasConfiguration' of type [org.springframework.hateoas.config.HateoasConfiguration$$EnhancerBySpringCGLIB$$22cbc87f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-18 20:36:54.039  INFO 8876 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-04-18 20:36:54.071  INFO 8876 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-04-18 20:36:54.071  INFO 8876 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-04-18 20:36:54.078  INFO 8876 --- [           main] o.a.catalina.core.AprLifecycleListener   : An older version [1.2.16] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.21]
2019-04-18 20:36:54.078  INFO 8876 --- [           main] o.a.catalina.core.AprLifecycleListener   : Loaded APR based Apache Tomcat Native library [1.2.16] using APR version [1.6.3].
2019-04-18 20:36:54.078  INFO 8876 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-04-18 20:36:54.078  INFO 8876 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-04-18 20:36:55.152  INFO 8876 --- [           main] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.0.2m  2 Nov 2017]
2019-04-18 20:36:55.436  INFO 8876 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-04-18 20:36:55.437  INFO 8876 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3165 ms
2019-04-18 20:36:56.035  INFO 8876 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-04-18 20:36:56.213  INFO 8876 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-04-18 20:36:56.470  INFO 8876 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
2019-04-18 20:36:56.603  INFO 8876 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.9.Final}
2019-04-18 20:36:56.604  INFO 8876 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-04-18 20:36:56.983  INFO 8876 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-04-18 20:36:57.365  INFO 8876 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2019-04-18 20:36:58.773  INFO 8876 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6a950a3b'
2019-04-18 20:36:58.776  INFO 8876 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-04-18 20:36:59.861  INFO 8876 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-18 20:36:59.929  WARN 8876 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-04-18 20:37:00.401  INFO 8876 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-18 20:37:00.405  INFO 8876 --- [           main] com.szcatic.Application                  : Started Application in 8.653 seconds (JVM running for 9.883)

六、打开postman

1.提交请求http://localhost:8080,显示结果如下:

{
    "_links": {
        "people": {
            "href": "http://localhost:8080/people{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile"
        }
    }
}

2.提交请求 http://localhost:8080/people,显示结果如下:

{
    "_embedded": {
        "people": []
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/people{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile/people"
        },
        "search": {
            "href": "http://localhost:8080/people/search"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 0,
        "totalPages": 0,
        "number": 0
    }
}

 3.提交请求 http://localhost:8080/people,请求方式为POST,请求参数为“{"firstName": "Frodo", "lastName": "Baggins"}”显示结果如下:

{
    "firstName": "Bilbo",
    "lastName": "Baggins",
    "_links": {
        "self": {
            "href": "http://localhost:8080/people/1"
        },
        "person": {
            "href": "http://localhost:8080/people/1"
        }
    }
}

4.提交请求 http://localhost:8080/people/1,显示结果如下:

{
    "firstName": "Bilbo",
    "lastName": "Baggins",
    "_links": {
        "self": {
            "href": "http://localhost:8080/people/1"
        },
        "person": {
            "href": "http://localhost:8080/people/1"
        }
    }
}

5.提交请求http://localhost:8080/people/search,显示结果如下:

{
    "_links": {
        "findByLastName": {
            "href": "http://localhost:8080/people/search/findByLastName{?name}",
            "templated": true
        },
        "self": {
            "href": "http://localhost:8080/people/search"
        }
    }
}

6.提交请求http://localhost:8080/people/search/findByLastName?name=Baggins,显示结果如下:

{
    "_embedded": {
        "people": [
            {
                "firstName": "Bilbo",
                "lastName": "Baggins",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/people/1"
                    },
                    "person": {
                        "href": "http://localhost:8080/people/1"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/people/search/findByLastName?name=Baggins"
        }
    }
}

7.提交请求http://localhost:8080/people/1,请求方式为“PUT”,请求参数为“{"firstName": "Bilbo", "lastName": "Baggins"}”,显示结果如下:

{
    "firstName": "Bilbo",
    "lastName": "Baggins",
    "_links": {
        "self": {
            "href": "http://localhost:8080/people/1"
        },
        "person": {
            "href": "http://localhost:8080/people/1"
        }
    }
}

8.提交请求http://localhost:8080/people/1,请求方式为“PATCH”,请求参数为“{"firstName": "Bilbo Jr."}”,显示结果如下:

{
    "firstName": "Bilbo Jr.",
    "lastName": "Baggins",
    "_links": {
        "self": {
            "href": "http://localhost:8080/people/1"
        },
        "person": {
            "href": "http://localhost:8080/people/1"
        }
    }
}

9.提交删除请求http://localhost:8080/people/1,请求方式为“DELETE”,显示结果如下:

 

再提交请求http://localhost:8080/people,查看结果,结果显示如下:

{
    "_embedded": {
        "people": []
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/people{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile/people"
        },
        "search": {
            "href": "http://localhost:8080/people/search"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 0,
        "totalPages": 0,
        "number": 0
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值