Construction of access REST interfaces for relational database based on Spring Boot

Will build a lesson based Spring Boot application, which provides an interface to access REST relational database - change search operations through the interface can be added or deleted to the User object stored in a relational database. Applications we use to create the Spring Data REST access interface.

Tip

Spring Data REST not only support relational databases, but also to support a variety of NoSQL database --Neo4j, Gemfile and MongoDB. They are outside the scope of the lesson, reference may Spring Data project.

Environmental prepare
a hand, said a text editor (such as Vim, Emacs, Sublime Text) or IDE (the Eclipse, Idea Intellij)
the Java environment (JDK 1.7 or later)
build tool Gradle 2.3
initialize the project directory
first create a project directory, the directory create a project profile Gradle the build.gradle:



buildscript {
    Repositories {
        jcenter ()
    }
    Dependencies {
        CLASSPATH ( "org.springframework.boot: Spring-Boot-Gradle-plugin: 1.2.5.RELEASE")
    }
}

Apply plugin: 'Java'
Apply plugin: 'Spring-Boot' 

JAR {
    = baseName 'Spring-Data-REST-Demo'
    Version = '1.0.0-the SNAPSHOT'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

Repositories {
    jcenter ()
}

Dependencies {
    the compile ( "org.springframework.boot: Spring-Boot-starter- REST-the Data ")
    the compile (" org.springframework.boot: the Spring-the Boot-Starter-the Data-JPA ")
    the compile (" com.h2database: h2 ")
}
in this document, the Spring Boot Gradle to use plug-ins to help us work to simplify some configurations:

providing Spring Boot framework defines dependence, they can be used (version number is not required) directly dependencies label
packaged application code and all of the dependencies into a single jar file
automatically search and main function as a start function jar file, jar file is a separate executable file
domain objects
In this lesson, domain objects are User-- it contains two fields --email and name, according to Gradle agreement, the object should be located in the project source folder src / main / java, and we put it in this tmy in the package:

the src / main / Java / TMY / User.java



@Entity
public class the User {

    @Id
    @GeneratedValue
    Private Long ID;

    Private String in Email;

    Private String name;

    // constructor, Getter / Setter methods omitted
}
@Entity annotations User indicates that is a JPA entity. User Each object has a unique identifier primary key id, which is the self-energizing Spring Data JPA automatically generated without manual handling it. Field of the above-described object defines a data storage format, Spring Data JPA mapped to the column name field relational database tables, suppose we have a User object:



User User User new new = (1L, "[email protected]", "Test name");
storage structure it in a relational database (here we use the class path is the default memory database H2Database) are:

the above mentioned id name Email
1         [email protected]         the Test the name
Repository
the art With the object User, to define a search operation can be added or deleted to change the Interface Repository:

the src / main / Java / TMY / UserRepository.java



Import org.springframework.data.repository.PagingAndSortingRepository;

public interface UserRepository the extends PagingAndSortingRepository <the User, Long> {

}
that we do not define any interface operating method, but directly inherited from PagingAndSortingRepository interface, which already comprise the customary methods of operation:

the findOne (Long ID)
the findAll ()
Save (the User User)
application when you start, Spring will automatically create the implementation of this interface. To invoke findOne (1L), for example, in fact, Spring Data JPA to help us generate such a sql query:



the SELECT * from the Users the WHERE the above mentioned id = 1;
and according to the query result set field name is mapped to a User object and returns. This is the ORM (Object Relation Mapper) framework helps us to simplify the basic method of data access layer in the development of ideas.

HTTP routing method while Spring Data Rest will bind response in Spring MVC and create User objects RESTful endpoint access / users:

GET / users User list information (corresponding to data from a relational database UserRepository, hereinafter the same)
the POST / Users Create a User object
GET / users / {id} to get a single User object
PUT / users / {id} Update User object single
DELETE / users / {id} delete individual User object
which is for the most basic of resources User additions and deletions to change search and access RESTful interface list, and after using Spring Data Rest project, we no longer need to prepare yourself these @Controller, for large some of the resources, these codes are pretty much the same, Spring Data Rest is precisely these common code extracted, we reduce the coding effort.

Run the application
to run applications based on Spring Boot is very simple, you do not need to rely on the code and labeled as traditional WAR package placed in the application server (Jetty, Tomcat), the Spring Boot packaged plug-in process, the embedded application server (default is tomcat). Therefore, the application itself is self-starting, we do not need to deploy it to an external application server:

src / main / the Java / the Hello / Application.java



Package Penalty for TMY;

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

@SpringBootApplication
public class {the Application

    static void main public (String [] args) {
        SpringApplication.run (Application.class, args);
    }
}
@SpringBootApplication Spring annotation is provided in the Boot, he corresponds to add the following comments:

@Configuration, indicates that Application is a Spring configuration object to configure Spring application context.
@ EnableAutoConfiguration, Spring Boot will be done automatically based on the behavior of some configuration classpath (classpath) and some property values, such as: the development of Web applications based on Spring MVC, need to add @EnableWebMvc in the configuration directly activate some of the default Web configuration, Once found Spring Boot runtime includes spring-webmvc dependent on the class path, it will automatically complete the basic configuration of a Web application - e.g. DispatcherServlet like configuration.
Spring application from the inform @ComponenScan to discover what position Spring member (@Component, @Service, @Configuration), etc.
After the configuration, the application running in two ways:

directly in the IDE main method
by Gradle packaged applications: gradle build run: java -jar build / libs / $ {appname} - {version} .jar
using the REST interface to create an object
After running the application, the database does not exist any data can be created by a User POST / users Interface:



$ the POST -H the -X-curl "the Type-the Content: file application / JSON" -d '{ "In Email": "Test @ test.com "," name ":" Ruici "} 'HTTP: // localhost: 8080 / Users
the HTTP / 1.1 201 the Created
Server: the Apache-Coyote / 1.1
the Location: HTTP: // localhost: 8080 / Users /. 1
Content- the Length: 0
a Date: Mon, 20 is 07:53:10 GMT, 2015 Jul-
parameter significance curl command is as follows:

the -X-parameter specifies the request type of method - GET, the POST, the PUT, the DELETE
-H Header parameter specifies the request, because here the contents of the request body is json object, so you must set the Type-content: the Application / json
-d to specify the contents of the request body
if not convenient to use curl under Windows, Chrome plugin recommended - a graphical interface tool Postman.

If you create successful, the server returns a 201 Created status code, and indicate the URL of the resource has been created in the Location header.

Get all objects


$ curl http: // localhost:


    "self" : {
      "href" : "http://localhost:8080/users{?page,size,sort}",
      "templated" : true
    }
  },
  "_embedded" : {
    "users" : [ {
      "email" : "[email protected]",
      "name" : "Ruici",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/1"
        }
      }
    } ]
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" :0   "In Email": "[email protected]",{$ curl HTTP: // localhost: 8080 / Users /. 1acquired single object}
  }







A field for storing the address of the user. In a relational database is usually to build a table to associate. Address table: ID Street City . 1 Yiheyuan Road Beijing the User table: ID name AddressID In Email

































1         [email protected]         the Test the Name 1
AddressID Address field indicates the associated table with id record 1, SQL query can be written:



the SELECT u.id AS userId, Email, name, a.id AS AddressID, City, Street
    from Inner the Join User A U address a.id = oN. 1 = u.addressId WHERE u.id
the Spring ORM based on the JPA the Data mapping principle, it can be defined by the association:



@Entity
public class the User {

    @Id
    @GeneratedValue
    Private Long ID;

    Private String in Email;

    Private String name;

    @OneToOne (= CascadeType.ALL in Cascade)
    Private the address address;

    // Constructors and Getter / Setter methods omitted

}
add a User object codes as follows:



@Autowired
Private UserRepository userRepository;

@Override
public void RUN (String ... args) throws Exception {
    the User User the User new new = ( "[email protected]", "the Hello World");
    user.setAddress (the Address new new ( "Beijing", "Yiheyuan Road. 5 "));

    userRepository.save (User);

}
That Spring Data JPA User object will automatically nested composition corresponding to the object persistence Address relational database tables. The same is true for queries.

After the above treatment, after running an application execution curl http: // localhost: 8080 / users, user can see the field already contains a composite object address.

Published 761 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/heima201907/article/details/104749412