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:
- Create a simple Spring Starter Project (File –> New –> Spring Starter Project). Select the language as “Kotlin” and Spring Boot version as “1.5.6”
- 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.
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
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”
}
POSTMAN will automatically add a header Content-Type as “application/json”, Now click on Send
You will get the Status as 200, which confirms that the Employee has been created.
Retrieve a single Employee
In POSTMAN, select GET method, and give the URL as “http://localhost:8080/employee/3”.
Retrieve all Employee
select GET method, and give the URL as “http://localhost:8080/employee”
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”
}
Delete Employee
select DELETE method, and give the URL as “http://localhost:8080/employee/4”
Leave a Reply