• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Boot Kotlin RESTful Web Services CRUD Example using Spring Data JPA + Maven

September 25, 2017 by javainterviewpoint Leave a Comment

In our previous example, we have learnt how to build a Hello World application in Kotlin using Spring Boot. In this example, we will go a bit further we will build a Spring Boot Kotlin RESTful Web Services using Spring Data JPA. Our application offers all four CRUD operations using the respective HTTP verbs POST, GET, PUT, DELETE

Based on the above HTTP verbs, our REST API does the below

  • /employee      –> Create Employee(POST)
  • /employee/1  –> Get Employee By Id (GET)
  • /employee      –> List of All Employees (GET)
  • /employee  –> Update Employee (PUT)
  • /employee/1  –> Delete Employee (DELETE)

Creating table

Create EMPLOYEE Table, simply Copy and Paste the following SQL query in the query editor to get the table created.

CREATE TABLE "EMPLOYEE" 
 ( 
    "ID" NUMBER(10) NOT NULL ENABLE, 
    "NAME" VARCHAR2(255 CHAR), 
    "AGE" NUMBER(10), 
    "DEPT" VARCHAR2(255 CHAR),   
     PRIMARY KEY ("ID")
 );
insert into Employee values(1,'JIP1',11,'IT');
insert into Employee values(2,'JIP2',22,'IT');
insert into Employee values(3,'JIP3',33,'IT');

Spring Boot Kotlin RESTful Web Services CRUD Example

As a pre-requisite, have the “Kotlin Plugin for Eclipse 0.8.2” plugin installed. The latest updated plugin is available in the below location. The Kotlin Plugin for Eclipse helps you write, run, debug and test programs in Kotlin language.

https://dl.bintray.com/jetbrains/kotlin/eclipse-plugin/last/

Folder Structure:

Kotlin REST API

  • Create a simple Spring Starter Project (File –> New –> Spring Starter Project). Select the language as “Kotlin” and Spring Boot version as “1.5.6”

Spring Boot with Kotlin 2

  • Now add the following dependency in the POM.xml
    <?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>com.javainterviewpoint</groupId>
    	<artifactId>SpringBootKotlin</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>SpringBootKotlin</name>
    	<description>Spring Boot Kotlin REST API</description>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.5.7.RELEASE</version>
    		<relativePath />
    	</parent>
    
    	<properties>
    		<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    		<java.version>1.8</java.version>
    		<kotlin.version>1.1.4-3</kotlin.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.jetbrains.kotlin</groupId>
    			<artifactId>kotlin-stdlib-jre8</artifactId>
    			<version>${kotlin.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.jetbrains.kotlin</groupId>
    			<artifactId>kotlin-reflect</artifactId>
    			<version>${kotlin.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>com.fasterxml.jackson.module</groupId>
    			<artifactId>jackson-module-kotlin</artifactId>
    			<version>2.9.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-rest</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-jpa</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>com.oracle</groupId>
    			<artifactId>ojdbc14</artifactId>
    			<version>11.2.0</version>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
    		<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    
    			</plugin>
    			<plugin>
    				<artifactId>kotlin-maven-plugin</artifactId>
    				<groupId>org.jetbrains.kotlin</groupId>
    				<version>${kotlin.version}</version>
    				<configuration>
    					<compilerPlugins>
    						<plugin>spring</plugin>
    					</compilerPlugins>
    					<jvmTarget>1.8</jvmTarget>
    				</configuration>
    				<executions>
    					<execution>
    						<id>compile</id>
    						<phase>compile</phase>
    						<goals>
    							<goal>compile</goal>
    						</goals>
    					</execution>
    					<execution>
    						<id>test-compile</id>
    						<phase>test-compile</phase>
    						<goals>
    							<goal>test-compile</goal>
    						</goals>
    					</execution>
    				</executions>
    				<dependencies>
    					<dependency>
    						<groupId>org.jetbrains.kotlin</groupId>
    						<artifactId>kotlin-maven-allopen</artifactId>
    						<version>${kotlin.version}</version>
    					</dependency>
    				</dependencies>
    			</plugin>
    		</plugins>
    	</build>
    </project>
  • Create a Kotlin classes SpringBootKotlinApplication.kt, Employee.kt, EmployeeRepository.kt and RestController.kt under com.javainterviewpoint folder.
  • Create application.properties file under src/main/resources directory.

Other interesting articles which you may like …

  • Spring Boot CommandLineRunner and ApplicationRunner
  • Spring Boot – How to Change Embedded Tomcat default port
  • Spring Boot CRUDRepository Example- Spring Data JPA
  • Fix missing src/main/java folder in Eclipse Maven Project
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services

applicaiton.properties

#Oracle Connection settings
spring.datasource.url=jdbc:oracle:thin:@rsh2:40051:mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

#JPA properties
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update

SpringBootKotlinApplication.kt

Add the below code in SpringBootKotlinApplication.kt

package com.javainterviewpoint

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan

@EnableAutoConfiguration
@ComponentScan
class SpringBootKotlinApplication

fun main(args: Array)
{
	SpringApplication.run(SpringBootKotlinApplication::class.java, *args)
	println(" **** Spring Boot Kotlin RESTful Web Services CRUD Example!!! *****")
}

Employee.kt

We will be receiving the response of Object Payload in the form of JSON rather than primitive values. REST uses JSON for both making requests and sending responses. So let’s create a data class to represent an object

package com.javainterviewpoint

import javax.persistence.Entity
import javax.persistence.Id

@Entity
data class Employee(
	@Id	
	var  id : Long =0,
	var  name : String="",
	var  age : Long =0,
	var  dept : String=""
		
)

Employee.kt acts as our data class with the id, name, age, dept property

RestController.kt

Our REST Endpoints looks like below

package com.javainterviewpoint

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.DeleteMapping

import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody

import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/employee")
class RestController(val employeeRepository: EmployeeRepository)
{
	@PostMapping
	fun saveEmployee(@RequestBody employee: Employee): Employee
	{
		return employeeRepository.save(employee)
	}

	@GetMapping("/{id}")
	fun getEmployee(@PathVariable id: Long): Employee
	{
		return employeeRepository.findOne(id)
	}

	@GetMapping
	fun getAllEmployees(): Iterable
	{
		return employeeRepository.findAll()
	}

	@PutMapping
	fun updateEmployee(@RequestBody employee: Employee)
	{
		employeeRepository.save(employee)
	}

	@DeleteMapping("/{id}")
	fun deleteEmployee(@PathVariable id: Long)
	{
		employeeRepository.delete(id)
	}
}

EmployeeRepository.kt

package com.javainterviewpoint

import org.springframework.data.repository.CrudRepository
		
interface EmployeeRepository : CrudRepository<Employee, Long>
{
	
}

We have extended CrudRepository in our EmployeeRepository class, that’s all we need to do. We will be able to perform CRUD Operations using the built-in methods of CrudRepository.

Running

Select the Project –>Run As –> Run Configuration –>Maven –> New. In the Main tab, key in the Goals as “spring-boot:run” and click on Run

Spring Boot with Kotlin 4

Output : 

Create an Employee

In POSTMAN,  select POST method, select the type as “application/json” and give the url as “http://localhost:8080/employee”. Add the JSON object which we are going to pass in the Body

{
“id”: 4,
“name”: “JIP4”,
“age”: 44,
“dept”: “IT”
}

Spring Boot Kotlin RESTful Web Services 1

POSTMAN will automatically add a header Content-Type as “application/json”, Now click on Send

Spring Boot Kotlin RESTful Web Services 2

You will get the Status as 200, which confirms that the Employee has been created.

Spring Boot Kotlin RESTful Web Services 3

Retrieve a single Employee

In POSTMAN,  select GET method, and give the URL as “http://localhost:8080/employee/3”. 

Spring Boot Kotlin RESTful Web Services 4

Retrieve all Employee

select GET method, and give the URL as “http://localhost:8080/employee”

Spring Boot Kotlin RESTful Web Services 5

Update Employee

select PUT method, select the type as “application/json” and give the url as “http://localhost:8080/employee”. Add the JSON object which we are going to pass in the Body

{
“id”: 4,
“name”: “JIP44444”,
“age”: 4444,
“dept”: “IT4”
}

Spring Boot Kotlin RESTful Web Services 6

Delete Employee

select DELETE method, and give the URL as “http://localhost:8080/employee/4”

Spring Boot Kotlin RESTful Web Services 7

    Download Source Code

Filed Under: J2EE, Java, Kotlin, Spring Boot Tagged With: Kotlin, RESTful Web Services, Spring Boot

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2022 · Java Interview Point - All Rights Are Reserved ·