Showing posts with label Restful web-services. Show all posts

In this post, we will create a Restful web-services which will use JPA to persist the data in the embedded database(h2). Also, you can read more on Restful web-services.

Adding pom.xml dependencies

We will add spring-boot-starter-jpa to manage dependencies. We will use h2 embedded database server for persistence.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

Creating entities

We have three entities in the example project viz. Product, Rating, User.

@Entity
@Table(name = "product_ratings", schema = "product")
public class Rating {
  @Id
  @GeneratedValue
  @Column(name="rating_id")
  private Long ratingId;
 
  private double rating;
 
  @Column(name="product_id")
  private String productId;
 
  @Column(name="user_id")
  private String userId;
 
  public Rating() {
  
  }
 
  public Rating(Long ratingId, double rating, String productId, String userId) {
    super();
    this.ratingId = ratingId;
    this.rating = rating;
    this.productId = productId;
    this.userId = userId;
  }
  //getters, setters, toString, hashCode, equals
}

@Entity annotation specifies that this is an entity class. @Table annotation specifies the primary table for an entity class. You can configure the table_name and schema using this annotation for the entity class. @Id specifies that this field is the primary key of the entity. @GeneratedValue specifies how primary key will be generated. @Column is used to specify the mapped column for the property or field. You can also configure if the property is unique, nullable, length, precision, scale and/or if you want to insert or update it in the table.

Creating Repositories

You can extend the JpaRepository, CrudRepository interface to create your repository.

@Transactional
public interface ProductRepository extends JpaRepository<Product, String> {

}

Here, I created a ProductRepository interface which extends JpaRepository interface. You may wonder that instead of writing a repository class, we have created an interface and where will this get the implementation? The simple answer is SimpleJpaRepository class. A Proxy is generated by Spring and all the request is catered by the SimpleJpaRepository.

This contains all the basic methods like find, delete, save, findAll and few sort related/ criteria based search methods. Could be a case that you need to write your own specific method and in my case finding all the ratings of product. This could be done as follows.

@Transactional
public interface RatingRepository extends JpaRepository<Rating, Long> {
  public Iterable<Rating> getRatingsByProductId(final String productId);
}

@EnableJpaRepositories annotation

This annotation will enable JPA repositories. This will scan for Spring Data repositories in annotated configuration class by default. You can also change the basePackages to scan in this annotation.

@SpringBootApplication
@EnableJpaRepositories
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}

In our example, we have used this annotation in our App class, so it will scan all the packages in and under com.gauravbytes.gkart

These are the few steps to create a simple JPA project. You can get the full code on Github.

Few important points

If you are using embedded server in the above example, then you may need to set the following configurations.

  • Adding schema.sql in the classpath, if you are using schema in your tables(entity classes). You can get sample here.
  • You can change the datasource name(by default testdb) and other properties. See org.springframework.boot.autoconfigure.jdbc.DataSourceProperties for full list of properties that you can configure.

In the previous posts, we have created a Spring Boot QuickStart, customized the embedded server and properties and running specific code after spring boot application starts.

Now in this post, we will create Restful webservices with Jersey deployed on Undertow as a Spring Boot Application.

Adding dependencies in pom.xml

We will add spring-boot-starter-parent as parent of our maven based project. The added benefit of this is version management for spring dependencies.

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

Adding spring-boot-starter-jersey dependency

This will add/ configure the jersey related dependencies.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

Adding spring-boot-starter-undertow dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

These are all the necessary spring-boot-starters we require to create Restful webservices with Jersey.

Creating a Root resource/ Controller class

What are Root resource classes?

Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE.

@Component
@Path("/books")
public class BookController {
  private BookService bookService;

  public BookController(BookService bookService) {
    this.bookService = bookService;
  }

  @GET
  @Produces("application/json")
  public Collection getAllBooks() {
    return bookService.getAllBooks();
  }

  @GET
  @Produces("application/json")
  @Path("/{oid}")
  public Book getBook(@PathParam("oid") String oid) {
    return bookService.getBook(oid);
  }

  @POST
  @Produces("application/json")
  @Consumes("application/json")
  public Response addBook(Book book) {
    bookService.addBook(book);
    return Response.created(URI.create("/" + book.getOid())).build();
  }

  @PUT
  @Consumes("application/json")
  @Path("/{oid}")
  public Response updateBook(@PathParam("oid") String oid, Book book) {
    bookService.updateBook(oid, book);
    return Response.noContent().build();
  }

  @DELETE
  @Path("/{oid}")
  public Response deleteBook(@PathParam("oid") String oid) {
    bookService.deleteBook(oid);
    return Response.ok().build();
  }
}

We have created a BookController class and used JAX-RS annotations.

  • @Path is used to identify the URI path (relative) that a resource class or class method will serve requests for.
  • @PathParam is used to bind the value of a URI template parameter or a path segment containing the template parameter to a resource method parameter, resource class field, or resource class bean property. The value is URL decoded unless this is disabled using the @Encoded annotation.
  • @GET indicates that annotated method handles HTTP GET requests.
  • @POST indicates that annotated method handles HTTP POST requests.
  • @PUT indicates that annotated method handles HTTP PUT requests.
  • @DELETE indicates that annotated method handles HTTP DELETE requests.
  • @Produces defines a media-type that the resource method can produce.
  • @Consumes defines a media-type that the resource method can accept.

You might have noticed that we have annotated BookController with @Component which is Spring's annotation and register it as bean. We have done so to benefit Spring's DI for injecting BookService service class.

Creating a JerseyConfiguration class

@Configuration
@ApplicationPath("rest")
public class JerseyConfiguration extends ResourceConfig {
  public JerseyConfiguration() {
  
  }
 
  @PostConstruct
  public void setUp() {
    register(BookController.class);
    register(GenericExceptionMapper.class);
  }
}

We created a JerseyConfiguration class which extends the ResourceConfig from package org.glassfish.jersey.server which configures the web application. In the setUp(), we registered BookController and GenericExceptionMapper.

@ApplicationPath identifies the application path that serves as the base URI for all the resources.

Registering exception mappers

Could there be a case that some exceptions occurs in the resource methods (Runtime/ Checked). You can write your own custom exception mappers to map Java exceptions to javax.ws.rs.core.Response.

@Provider
public class GenericExceptionMapper implements ExceptionMapper {

  @Override
  public Response toResponse(Throwable exception) {
    return Response.serverError().entity(exception.getMessage()).build();
  }
}

We have created a generic exception handler by catching Throwable. Ideally, you should write finer-grained exception mapper.

What is @Provider annotation?

It marks an implementation of an extension interface that should be discoverable by JAX-RS runtime during a provider scanning phase.

We have also created service BookService, model Book also. You can grab the full code from Githib.

Running the application

You can use maven to directly run it with mvn spring-boot:run command or can create a jar and run it.

Testing the rest endpoints

I have used PostMan extension available in chrome brower to test rest services. You can use any package/ API/ software to test it.

This is how we create Restful web-services with Jersey in conjuction with Spring Boot. I hope you find this post informative and helpful to create your first but not last Restful web-service.