Connecting Spring Boot and PostgreSQL database – Part 2

Following on from part 1, we will now make a Spring Boot rest service.

Create a project directory and we will work inside of their.

Inside your project directory, create this directory structure:

$ mkdir -p src/main/java/users

$ mkdir -p src/main/resources

We will be using maven to manage our dependencies, so create in the top level a pom.xml with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework</groupId>
    <artifactId>gs-postgresql-data</artifactId>
    <version>0.1.0</version>

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

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

        <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->

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

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

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

</project>

Then, we will create an application.properties inside our resources directory:

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=update

This allows us to update the database rather than create a new one every time with update instead of create.

Now, create the following classes inside the users directory:

Users.java

package users;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "users")
public class Users implements Serializable {

    private static final long serialVersionUID = -3009157732242241606L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

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

    protected Users() {
    }

    public String getUsername() {
        return username;
    }

    public Users(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return String.format("Customer[id=%d, username='%s']", id, username);
    }
}

UserRepository.java

package users;

import org.springframework.data.repository.CrudRepository;

/**
 *  This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
 *  CRUD refers Create, Read, Update, Delete
 */
public interface UserRepository extends CrudRepository<Users, Long> {

}

UserController.java

package users;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(path="/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping(path="/add")
    public @ResponseBody String addNewUser (@RequestParam String username) {
        Users testuser = new Users(username);
        userRepository.save(testuser);
        return "done";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable getAllUsers() {
        return userRepository.findAll();
    }
}

Application.java

package users;

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

Let’s test the application works.

Run:
$ mvn clean install spring-boot:run

Then, in a browser, run navigate to http://localhost:8080/users/add?username=johndoe then navigate to http://localhost:8080/users/all and this should display all the usernames stored in the database in json format.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s