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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jre8</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-reflect</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> </dependencies> |
2. Configure Spring JPA
Open application.properties, add:
1 2 3 4 |
spring.datasource.url=jdbc:postgresql://localhost/testdb spring.datasource.username=postgres spring.datasource.password=123 spring.jpa.generate-ddl=true |
3. Create DataModel Class
Under package model, create Customer class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kotlination.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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.kotlination.jpapostgresql.repo import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository import com.kotlination.jpapostgresql.model.Customer @Repository interface CustomerRepository : CrudRepository<Customer, Long> { fun findByLastName(lastName: String): Iterable<Customer> } |
5. Create Web Controller
Under package controller, create a controller that receives requests from client, using repository to update/get data and return results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.kotlination.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.kotlination.jpapostgresql.repo.CustomerRepository import com.kotlination.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:
1 2 3 |
<S extends T> S save(S entity); //for @RequestMapping("/save") T findOne(ID id); //for @RequestMapping("/findbyid") Iterable<T> findAll(); //for @RequestMapping("/findall") |
And the method findByLastName that we create in our interface CustomerRepository.
1 |
fun findByLastName(lastName: String): Iterable<Customer> |
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:
Request 2
http://localhost:8080/findall
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
[ { "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
1 2 3 4 5 |
{ "firstName": "Peter", "lastName": "Davis", "id": 26 } |
Request 4
http://localhost:8080/findbylastname/Smith
1 2 3 4 5 6 7 8 9 10 11 12 |
[ { "firstName": "Jack", "lastName": "Smith", "id": 22 }, { "firstName": "Kim", "lastName": "Smith", "id": 24 } ] |