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 create Kotlin Spring JPA application with PostgreSQL using Spring Boot.

Related posts:
Kotlin – How to start Kotlin development with SpringBoot + Maven + SpringToolSuite
Kotlin Spring MVC RequestMapping RESTful APIs with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping | SpringBoot Example
How to use Spring JPA with PostgreSQL | Spring Boot


I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.6RELEASE
– Kotlin 1.1.4

II. Overview

1. Goal

spring-jpa-postgresql-goal

2. Project Structure

spring-jpa-postgresql-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:
kotlin springboot jpa postgresql - create project

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

	
		true
		UTF-8
		UTF-8
		1.8
		1.1.4
	

	
		
			org.springframework.boot
			spring-boot-starter
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
		
			org.postgresql
			postgresql
			runtime
		
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
		
			org.jetbrains.kotlin
			kotlin-stdlib-jre8
			${kotlin.version}
		
		
			org.jetbrains.kotlin
			kotlin-reflect
			${kotlin.version}
		
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	
2. Configure Spring JPA

Open application.properties, add:

spring.datasource.url=jdbc:postgresql://localhost/testdb
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.generate-ddl=true

# Pretty-print JSON responses
spring.jackson.serialization.indent_output=true

Note: spring.jackson.serialization.indent_output=true is used to enable Json pretty-print of Jackson library.

3. Create DataModel Class

Under package model, create Customer class:

package com.javasampleapproach.jpapostgresql.model

import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType

@Entity
class Customer(
		val firstName: String,
		val lastName: String,
		@Id @GeneratedValue(strategy = GenerationType.AUTO)
		val id: Long = -1) {
	
	private constructor() : this("", "")
}

– 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:

package com.javasampleapproach.jpapostgresql.repo

import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository

import com.javasampleapproach.jpapostgresql.model.Customer


@Repository
interface CustomerRepository : CrudRepository {

	fun findByLastName(lastName: String): Iterable
}
5. Create Web Controller

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

package com.javasampleapproach.jpapostgresql.controller

import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.beans.factory.annotation.Autowired

import com.javasampleapproach.jpapostgresql.repo.CustomerRepository
import com.javasampleapproach.jpapostgresql.model.Customer

@RestController
class WebController {

	@Autowired
	lateinit var repository: CustomerRepository

	@RequestMapping("/save")
	fun save(): String {
		repository.save(Customer("Jack", "Smith"))
		repository.save(Customer("Adam", "Johnson"))
		repository.save(Customer("Kim", "Smith"))
		repository.save(Customer("David", "Williams"))
		repository.save(Customer("Peter", "Davis"))

		return "Done"
	}

	@RequestMapping("/findall")
	fun findAll() = repository.findAll()

	@RequestMapping("/findbyid/{id}")
	fun findById(@PathVariable id: Long)
			= repository.findOne(id)

	@RequestMapping("findbylastname/{lastName}")
	fun findByLastName(@PathVariable lastName: String)
			= repository.findByLastName(lastName)
	
}

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

 S save(S entity); //for @RequestMapping("/save")
T findOne(ID id); //for @RequestMapping("/findbyid")
Iterable findAll(); //for @RequestMapping("/findall")

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

fun findByLastName(lastName: String): Iterable
6. Run & check Result

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

Request 1
http://localhost:8080/save
Using pgAdmin III, open testdb database, we will see customer table with 3 columns:
spring-jpa-postgresql-table-result

Request 2
http://localhost:8080/findall

[
   {
      "firstName": "Jack",
      "lastName": "Smith",
      "id": 22
   },
   {
      "firstName": "Adam",
      "lastName": "Johnson",
      "id": 23
   },
   {
      "firstName": "Kim",
      "lastName": "Smith",
      "id": 24
   },
   {
      "firstName": "David",
      "lastName": "Williams",
      "id": 25
   },
   {
      "firstName": "Peter",
      "lastName": "Davis",
      "id": 26
   }
]

Request 3
http://localhost:8080/findbyid/26

{
   "firstName": "Peter",
   "lastName": "Davis",
   "id": 26
}

Request 4
http://localhost:8080/findbylastname/Smith

[
   {
      "firstName": "Jack",
      "lastName": "Smith",
      "id": 22
   },
   {
      "firstName": "Kim",
      "lastName": "Smith",
      "id": 24
   }
]

IV. Source Code

KotlinSpringJpaPostgresql



By grokonez | September 1, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*