Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

REST Server with Spring Data, Spring Boot and PostgreSQL

This article will create and configure a REST server with the Spring Data for the manipulation of data to PostgreSQL database and the Spring Boot used to configure and initialize the application easily and quickly.

Spring Data is a set of Spring projects for manipulating data in various ways, including relational databases such as MySQL and PostgreSQL as well as in NoSQL databases like MongoDB and Redis. One such project is the Spring Data JPA for developing applications with the Java Persistence API (JPA), which allows the implementation of a data model object-relational mapping.

Besides the mapping, the framework also allows the development of methods for data access with little or no code necessary for its development, which greatly facilitates the development of application and increases the productivity of programmers.

Combined with Spring Data JPA, you can use Spring Boot for the quick and easy configuration of the application and the availability of a data repository with a Rest API. Spring Boot allows you to run the application without the need for any external tool and with virtually no configuration required. For example, this tool internally runs the application server, no configuration is necessary, it also facilitates the configuration of the Spring framework in the application, among many other things.

This article will show how to configure the application using Spring Boot, and also how to develop an application using Spring Data JPA. It will also be shown the server running and returning data in JSON standard.

Configuration of the Application

The sample application of this article was developed in Eclipse IDE and using maven for configuring dependencies, Listing 1 shows the pom.xml file that should contain the spring-boot-starter-data-rest dependencies that is the library for creation of the REST server with Spring Boot, the dependency spring-boot-starter-data-jpa which is the dependence of Spring Data and the postgresql dependency that is the driver to connect to the database.

Listing 1. pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mrbool.spring-test</groupId>
	<artifactId>server</artifactId>
	<version>0.0.1</version>      

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

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

  <dependencies>
	  <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>org.postgresql</groupId>
				<artifactId>postgresql</artifactId>
				<version>9.4-1200-jdbc4</version>
		  </dependency>
  </dependencies>

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

  <repositories>
	  <repository>
		  <id>spring-releases</id>
		  <url>https://repo.spring.io/libs-release</url>
	  </repository>
  </repositories>
  <pluginRepositories>
	  <pluginRepository>
		  <id>spring-releases</id>
		  <url>https://repo.spring.io/libs-release</url>
	  </pluginRepository>
  </pluginRepositories>
</project>

To run the application you must have the PostgreSQL database installed, if the reader prefers, you can use another database like MySQL or SQL Server, simply change the pom configuration to import the Driver dependence of the desired database.

Application Development

With everything set, we can start the implementation of the application, it will be used for two model classes, the Customer class and the Purchase class to represent the objects that will be stored in the database. Listing 2 shows the client class with attributes id, name, address and CARD ID in association and relationship with a shopping list. This class is a JPA entity, so that's why we used @Entity @Id, @GeneratedValue, @OneToMany and @JoinColumn annotations.

Listing 2. Customer Class

package com.mrbool.server.model;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

@Entity
public class Customer {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)    
	private Long id;
	
	private String name;

	private String address;
	
	private String cardId;

	@OneToMany(targetEntity=Purchase.class, fetch=FetchType.EAGER)
	@JoinColumn(name="client_id")
	private List<Purchase> purchases;
	
	public Long getId() {
		  return id;
	}

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

	public String getName() {
		  return name;
	}

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

	public String getAddress() {
		  return address;
	}

	public void setAddress(String address) {
		  this.address = address;
	}

	public String getCardId() {
		  return cardId;
	}

	public void setCardId(String cardId) {
		  this.cardId = cardId;
	}

	public List<Purchase> getPurchases() {
		  return purchases;
	}

	public void setPurchases(List<Purchase> purchases) {
		  this.purchases = purchases;
	}
}

The Purchase class is also a JPA entity, and therefore has the same annotations of the Customer class. Listing 3 shows the code for this class, which has the id, totalValue and numberOfProducts attributes.

Listing 3. Class Purchase

package com.mrbool.server.model;

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

@Entity
public class Purchase {

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)    
	private Long id;
	
	private float totalValue;
	private int numberOfProducts;
	
	public Long getId() {
		  return id;
	}

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

	public float getTotalValue() {
		  return totalValue;
	}

	public void setTotalValue(float totalValue) {
		  this.totalValue = totalValue;
	}

	public int getNumberOfProducts() {
		  return numberOfProducts;
	}

	public void setNumberOfProducts(int numberOfProducts) {
		  this.numberOfProducts = numberOfProducts;
	}
}

Now, with Spring Data we can develop the repositories that are interfaces where the methods of data access are defined, for this is necessary to extend the PagingAndSortingRepository interface, which already offers several methods for data access in addition we can also create new methods likefindByName and findByNameOrderByName. With Spring Data we don't need to implement nothing else, when following the pattern names, the framework already understand what the method should do. If the developer wants to implement some very different query, it can use the @Query annotation as shown in Listing 4.

This interface is also necessary to place the @RepositoryRestResource annotation indicating that a REST server will be created using the methods defined in the interface.

Listing 4. Class ClientRepository

package com.mrbool.server.repository;

import java.util.List;

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

import com.devmedia.server.model.Client;

@RepositoryRestResource(collectionResourceRel = "client", path = "clients")
public interface ClientRepository extends PagingAndSortingRepository<Client, Long> {
	/**
	 * Method that returns a lista of clients doing a search by the passed name parameter.
	 *  
	 * @param name
	 * @return list of clients
	 */
	List<Client> findByName(@Param("name") String name);
	
	/**
	 * Method that returns a client with only its name doing a search by the passed id parameter.
	 * 
	 * @param id
	 * @return client of the id passed as parameter.
	 */   
    @Query("SELECT c.Name FROM Client c where c.id = :id") 
	Client findNameById(@Param("id") Long id);
	
	/**
	 * Method that returns a list of clients doing a search by the passed name parameter and sorting them by the name.
	 *  
	 * @param name
	 * @return list of clients
	 */
	List<Client> findByNameOrderByName(@Param("name") String name);

}

The server is almost complete, missing just the creation of the class to launch the application, for this, it will be used Spring Boot, so just put the line SpringApplication.run (Application.class, args) in the main method of the class, and Spring Boot starts tomcat with the application created already working. To indicate that this is a class of Spring Boot, you must place the @SpringBootApplication annotation. The @EntityScan annotation indicates the package where the JPA classes are and @EnableJpaRepositories annotation indicates the package where the repository classes are. Listing 5 shows the code for this class.

Listing 5. Class Application

package com.mrbool.server.run;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EntityScan(basePackages = {
		  "com.mrbool.server.model"
		  })
@EnableJpaRepositories(basePackages = {
		  "com.mrbool.server.repository"
		  })
public class Application {

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

The last step in the development of the application is to configure the database, for this you must create the application.properties file, which must be created in the src/main/resourcesdirectory of the project. In this file are configured the driver, the URL, the user name and database password and the port that tomcat will run. Listing 6 shows an example of this file if you are using another database, you must change the driverClasseName and the connection URL.

Listing 6. application.properties file

spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.database.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/your-database
spring.datasource.username=postgres
spring.datasource.password=postgres
server.port=8080

If everything is fine, just run the application, the database is automatically created for the create-drop optionplaced on the application.properties file. To access the services we can use a browser like Chrome or can be made a implementation of a REST client as well. For example, the findByName method was exposed as a service. To access it simply use the URL http://localhost:8080/customers/search/findByName?name=John. The answer for this call is in Listing 7, and it is sent as a JSON file. You can see that in addition to the customer, it was also returned purchases that are related to client John.

Listing 7. Response of findByName call

{
	"_embedded" : {
	  "client" : [ {
		"name" : "John",
		"address" : "13th Avenue, 1234",
		"cardId" : "1275634",
		"purchases" : [ {
		  "totalValue" : 100.0,
		  "numberOfProducts" : 5
		}, {
		  "totalValue" : 500.0,
		  "numberOfProducts" : 2
		} ],
		"_links" : {
		  "self" : {
			"href" : "http://localhost:8080/clients/1"
		  },
		  "client" : {
			"href" : "http://localhost:8080/clients/1"
		  }
		}
	  } ]
	},
	"_links" : {
	  "self" : {
		"href" : "http://localhost:8080/clients/search/findByName?name=John"
	  }
	}
}

To see all the available services you can access the URL http://localhost:8080/customers/search, which returns all available services. Listing 8 shows the answer to that request. It's possible to see that the findNomeByID, findByNameOrderByName and findByName services were returned, which are the methods declared in the repository interface. Moreover, in the returned file are displayed the parameters required for each service, such as {?id} and {?name}.

Listing 8. Response of the request to discover the available services

{
  "_links" : {
    "findNameById" : {
      "href" : "http://localhost:8080/clients/search/findNameById{?id}",
      "templated" : true
    },
    "findByNameOrderByName" : {
      "href" : "http://localhost:8080/clients/search/findByNameOrderByName{?name}",
      "templated" : true
    },
    "findByName" : {
      "href" : "http://localhost:8080/clients/search/findByName{?name}",
      "templated" : true
    },
    "self" : {
      "href" : "http://localhost:8080/clients/search"
    }
  }
}

In addition to the services created, it is also possible to search by customer id, just use the URL http://localhost:8080/customers/id and the server returns a JSON file with all the customer data for that id. For example, in Listing 9 was made the request to http://localhost:8080/clients/2, which returned the customer data that has the id = 2.

Listing 9. Response of the request to the client id = 2

{
  "name" : "Luiz",
  "address" : "13th Avenue, 1234",
  "cardId" : "1234345",
  "purchases" : [ {
    "totalValue" : 600.0,
    "numberOfProducts" : 7
  }, {
    "totalValue" : 200.0,
    "numberOfProducts" : 2
  }, {
    "totalValue" : 300.0,
    "numberOfProducts" : 8
  } ],
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/clients/2"
    },
    "client" : {
      "href" : "http://localhost:8080/clients/2"
    }
  }
}

Conclusion

This article has shown that it is quite easy to develop a REST server using the frameworks Spring Data and Spring Boot. The application developed in this article used the PostgreSQL database, but any relational database can be used with virtually no change in the code. To show the functioning of the server developed were shown several requests made and the result returned.

I hope this article is helpful to you! See you later!

Links

Spring Data - Official site of the Spring Data project

http://projects.spring.io/spring-data/

Spring Date REST - Official Page of theSpring Data RESTproject

http://projects.spring.io/spring-data-rest/

PostgreSQL - Official Page of PostgreSQL database

http://www.postgresql.org/

Spring Boot - Official Page of the Spring Boot project

http://projects.spring.io/spring-boot/



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login