springboot使用REST访问JPA数据

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

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

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

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.jayway.jsonpath
            json-path
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-data-rest
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            com.h2database
            h2
        
        
        
		    org.junit.jupiter
		    junit-jupiter-engine
		    test
		
		
		    org.junit.platform
		    junit-platform-runner
		    test
		
    

    
        1.8
    


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

二、创建实体类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 {

	List 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"
        }
    }
}

springboot使用REST访问JPA数据_第1张图片

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
    }
}

springboot使用REST访问JPA数据_第2张图片

 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"
        }
    }
}

springboot使用REST访问JPA数据_第3张图片

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"
        }
    }
}

springboot使用REST访问JPA数据_第4张图片

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"
        }
    }
}

springboot使用REST访问JPA数据_第5张图片

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"
        }
    }
}

springboot使用REST访问JPA数据_第6张图片

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"
        }
    }
}

springboot使用REST访问JPA数据_第7张图片

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

springboot使用REST访问JPA数据_第8张图片

 

再提交请求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
    }
}

springboot使用REST访问JPA数据_第9张图片

你可能感兴趣的:(springboot使用REST访问JPA数据)