Spring Boot + REST Jersey (Adding Spring data) Part 2


In this post, I will explain in an easy way how to configure and use Spring data with Spring boot. In order to do it we will use a previous example Spring Boot + REST Jersey Part 1.

Step 1 (Including maven dependencies)

Spring boot generated starter dependencies, this dependencies contain all the necessary resources to use each of the spring modules in the easiest way. The versions of the necessary dependencies are not required because they come from the spring boot parent project. To configure Spring Data is necessary add the following dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Step 2 (Configuring the datasource)

The next step will be create a file named application.properties, in this file we will define the information of the database connection, in this example we will show how to create a datasource for MySQL.

spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_users
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

In the file application.properties is possible to define multiples configurations for spring boot like database information, ports, context path, etc. This file can be a .properties or a .yml file.

Step 3 (Configuring repositories)

Spring Data uses repositories to access to the information, now we have to define the java package that will contain all the repositories, in this example will be com.raidentrance.repositories.

/**
 *
 */
package com.raidentrance.config;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author raidentrance
 *
 */
@EnableTransactionManagement
@EnableJpaRepositories("com.raidentrance.repositories")
public class SpringDataConfig {

}

Step 4 (Creating the tables and data for the example)

The application will use a table named user with the following structure:

CREATE TABLE USER(
USER_ID INTEGER PRIMARY KEY AUTO_INCREMENT,
USERNAME VARCHAR(100) NOT NULL,
PASSWORD VARCHAR(100) NOT NULL
);

Now we have to insert some sample data:

INSERT INTO USER (USERNAME,PASSWORD)VALUES('raidentrance','superSecret');
INSERT INTO USER (USERNAME,PASSWORD)VALUES('john','smith');
INSERT INTO USER (USERNAME,PASSWORD)VALUES('juan','hola123');

Step 6 (Creating JPA entities)

Once we configured Spring Data, created the tables and populated them we have to create a JPA entity to represent the relational model in the domain model by creating the entity User.java.

/**
 *
 */
package com.raidentrance.entities;

import java.io.Serializable;

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

/**
 * @author raidentrance
 *
 */
@Entity
@Table(name = "USER")
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USER_ID")
    private Integer idUser;

    @Column(name = "USERNAME")
    private String username;

    @Column(name = "PASSWORD")
    private String password;

    private static final long serialVersionUID = -5290198995172316155L;

    public Integer getIdUser() {
        return idUser;
    }

    public void setIdUser(Integer idUser) {
        this.idUser = idUser;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [idUser=" + idUser + ", username=" + username + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((idUser == null) ? 0 : idUser.hashCode());
        result = prime * result + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (idUser == null) {
            if (other.idUser != null)
                return false;
        } else if (!idUser.equals(other.idUser))
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

}

Step 7 (Creating a Spring data repository)

Now we have to create a Spring data repository, this will be used to access to the database:

/**
 *
 */
package com.raidentrance.repositories;

import org.springframework.data.repository.CrudRepository;

import com.raidentrance.entities.User;

/**
 * @author raidentrance
 *
 */
public interface UserRepository extends CrudRepository<User, Integer> {
}

UserRepository is an interface, the most common question is, do I have to create a class that implements the UserRepository interface ? the answer is NO, the only thing that we need to do is to define the interface and Spring Data will create the implementation for it.

Step 8 (Using the JPA Repository)

The last part is to use the repository in the application, in order to do it, we will integrate the component in the web service REST created in the part 1 of the tutorial Spring Boot + REST Jersey Part 1.

/**
 *
 */
package com.raidentrance.resource;

import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.raidentrance.entities.User;
import com.raidentrance.repositories.UserRepository;
import jersey.repackaged.com.google.common.collect.Lists;

/**
 * @author raidentrance
 *
 */

@Component
@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    @Autowired
    private UserRepository userRepository;

    @GET
    public Response getUsers() {
        ArrayList<User> users = Lists.newArrayList(userRepository.findAll());
        return Response.ok(users).build();
    }

}

In order to use the repository created we will use the annotation @Autowired, as you can see the method used to get all the users is findAll(), this method is not defined in the interface created, it is defined in the parent interface named CrudRepository.

Step 9 (Testing all together)

In order to test the project the only thing you need to do is execute the class SpringBootSampleApplication, when it finishes you have to execute the endpoint http://localhost:8080/users.

Output

[
{
idUser: 1,
username: "raidentrance",
password: "superSecret"
},
{
idUser: 2,
username: "john",
password: "smith"
},
{
idUser: 3,
username: "juan",
password: "hola123"
}
]

Next steps

In the following posts we will explain:

  • How to return a DTO instead of a list of entities in the web service REST
  • Add ExceptionMappers for error handling
  • Add support for HATEOAS
  • Add spring security
  • Add logging
  • Add different profiles for different environments

You can find the complete code in the following link https://github.com/raidentrance/spring-boot-example/tree/part2-adding-springdata

If you want to learn more about web services we recommend the following books:

Autor: Alejandro Agapito Bautista

Twitter: @raidentrance

Contacto:raidentrance@gmail.com

Anuncios

1 comentario »

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s