Kotlin – Spring JPA + Postgresql | Spring Boot Example

Spring JPA helps us improve our codes and reduce efforts for development and maintenance. It supports us the ways to write interface for repositories and custom finder methods, the implementation will be done automatically by Spring Framework. This Kotlin tutorial shows you how to use Spring JPA with PostgreSQL using Spring Boot.

>>> Refer to: JavaSampleApproach.com

I. Technology

– Java 1.8
– Kotlin 1.1.2
– Maven 3.3.9
– Spring Tool Suite 3.8.4.RELEASE
– Spring Boot 1.5.3.RELEASE

II. Overview

1. Goal


2. Project Structure


Customer class corresponds to entity and table customer.
CustomerRepository is an interface extends CrudRepository, will be autowired in WebController for implementing repository methods and custom finder methods.
WebController is a REST Controller which has request mapping methods for RESTful requests such as: save, findall, findbyid, findbylastname.
– Configuration for Spring Datasource and Spring JPA properties in application.properties
Dependencies for Spring Boot, PostgreSQL and Kotlin in pom.xml

3. Step to do

– Create Spring Boot project & add Dependencies
– Configure Spring JPA
– Create DataModel Class
– Create Spring JPA Repository Interface
– Create Web Controller
– Create PostGreSQL table
– Run & check Result

III. Practice

1. Create Spring Boot project & add Dependencies

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:

Click Next and Finish, then our project will be created successfully.
Open pom.xml and add Dependencies:

2. Configure Spring JPA

Open application.properties, add:

3. Create DataModel Class

Under package model, create Customer class:

– Annotation @Entity indicates that Customer is an Entity.
Table customer and column: id, first_name, last_name will be created automatically.

@ID specifies the primary key and @GeneratedValue indicates generation strategy for value of primary key.

– Constructor method will be used by Spring JPA.

4. Create Spring JPA Repository Interface

Under package repo, create a interface that helps us do all CRUD functions for Customer class:

5. Create Web Controller

Under package controller, create a controller that receives requests from client, using repository to update/get data and return results.

In the web controller methods which are annotated by @RequestMapping, we have used some methods of autowired repository which are implemented interface CrudRepository:

And the method findByLastName that we create in our interface CustomerRepository.

6. Run & check Result

– Config maven build:
clean install
– Run as Kotlin Application
– Check results:

Request 1
Using pgAdmin III, open testdb database, we will see customer table with 3 columns:

Request 2

Request 3

Request 4

IV. Source Code

Download it: KotlinSpringJpaPostgresql (6KB)

Add Comment