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="" xmlns:xsi=""




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







Then, we will create an inside our resources directory:


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:

package users;

import javax.persistence.*;

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

    private static final long serialVersionUID = -3009157732242241606L;
    @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;

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

package users;


 *  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> {


package users;

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

public class UserController {

    private UserRepository userRepository;

    public @ResponseBody String addNewUser (@RequestParam String username) {
        Users testuser = new Users(username);;
        return "done";

    public @ResponseBody Iterable getAllUsers() {
        return userRepository.findAll();

package users;

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

public class Application {

    public static void main(String[] args) {, args);

Let’s test the application works.

$ 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.


Leave a Reply

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

You are commenting using your 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