Updated April 4, 2023
Introduction to Kotlin Exposed
Kotlin exposed is one of the frameworks and it’s the open-source library that provides an idiomatic kotlin API for some relational databases that can be used to implement while using a smooth interface that’s out of the scope and it is the differences among from the database vendors it has own JDBC connection library it provides us the database class that allows for several connection default methods for handling the data model is mapped each table is represented by the individual kotlin object that can be extended using the table class and also the parameter is passed to the table name.
Syntax
In kotlin language, we used default classes, methods, and variables to implement the application. The kotlin exposed is one of the ways to perform the user and data transactions using kotlin language.
Entities.kt:
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
class name
{
@Id
val varname:datatype= value
}
Controller.kt:
import org.springframework.web.bind.annotation.*
@RestController
class name1(val eg: value){
@PostMapping("/values")
fun method(@RequestBody vars: entity)
{
}
}
Repositiories.kt:
import org.springframework.data.repository.CrudRepository
interface repositoryname : CrudRepository<Entity,datatype>
{
fun method(vars2:datatype) : Entity
}
main.kt:
class names2
fun main(args: Array<String>) {
runApplication<names2>(*args)
}
The above codes are the basic syntax and dataflow using databases and web services.
How does exposed work in Kotlin?
The kotlin exposed is the open-source library is licensed using Apache and it provides the idiomatic kotlin API for some relational database implementations while smoothing and it came out the differences among the other database vendors. It is the framework and it can be used for both as a high-level DSL using the SQL and it’s the lightweight ORM (Object-Relational Mapping) it will cover under all the usages. Generally Exposed it’s not yet the tools like Maven central and so we have to use the dedicated repository. The in-build database like h2 to store and retrieve the data from the client-server transactions. For connecting the database we can use the default connections and drivers to pass the parameter in the database class so that it will invoke the connection that does not establish the connection to the database being right away. If we want to add additional parameters then the method will use the different overload of the connect method that gives the full control access over the acquisition of the database connection. The version of the connection should be named as the closure parameter and it is exposed to invoke the closure whenever it needs the new database connection.
Example #1
Entities.kt:
package com.example.July30th
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
class Electrical
{
@Id
val id: Long=-1
val name: String =""
}
ElectricalController.kt:
package com.example.July30th
import org.springframework.web.bind.annotation.*
@RestController
class ElectricalController(val repo: ElectricalRepositories){
@PostMapping("/elect")
fun addName(@RequestBody elect: Electrical)
{
repo.save(elect)
}
@GetMapping("/elect")
fun getName() : List<Electrical>
{
return repo.findAll().toList();
}
@GetMapping("/elect/{name}")
fun getElectricalByName(@PathVariable("name")name:String) = repo.findByName(name)
}
Repositories.kt:
package com.example.July30th
import org.springframework.data.repository.CrudRepository
interface ElectricalRepositories : CrudRepository<Electrical,Long>
{
fun findByName(name:String) : Electrical
}
July30thApplication.kt:
package com.example.July30th
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class July30thApplication
fun main(args: Array<String>) {
println("Welcome To My Domain its the first example that related to the kotlin expose")
runApplication<July30thApplication>(*args)
}
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>July30th</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>July30th</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<kotlin.version>1.5.21</kotlin.version>
</properties>
<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>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
<plugin>jpa</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Output:
Postman tool Request and Response for Post method:
Postman tool Request and Response for Get method:
In the above example, we used to add and retrieve the user data using post man tool.
Example #2
Entities. kt:
package com.example.July30th
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Table(name = "julyTest")
public class Student(
@Id
val id: Long = -1,
@Column(name = "studentName")
val studentName: String = "",
@Column(name = "averageMarks")
val averageMarks: Int
){
override fun toString(): String{
return "Customer[id=${id}, studentName=${studentName}, averageMarks=${averageMarks}]"
}
}
Repositories. kt:
package com.example.July30th
import org.springframework.data.repository.CrudRepository
import com.example.July30th.Student
interface StudentRepository: CrudRepository<Student, Long>{
fun findByStudentName(studentName: String): List<Student>
}
StudentContoller.kt:
package com.example.July30th
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
class StudentController {
@Autowired
lateinit var repository: StudentRepository
@RequestMapping("/save")
fun studDetails(): String{
repository.save(Student(1, "Siva", 400))
repository.save(Student(2, "Raman", 390))
repository.save(Student(3, "Sivaraman", 450))
repository.save(Student(4, "xy", 460))
repository.save(Student(5, "Yz", 350))
return "Student details saved successfully"
}
@RequestMapping("/showAll")
fun showAll(): String{
var output = ""
for(stud in repository.findAll()){
output += stud.toString() + "</br>"
}
return output
}
@RequestMapping("/findById")
fun findById(@RequestParam("id") id: Long): String{
return repository.findById(id).toString()
}
@RequestMapping("/findByName")
fun findByName(@RequestParam("name") name: String): String{
var result = ""
for(stud in repository.findByStudentName(name)){
result += stud.toString() + "</br>"
}
return result
}
}
july30thApplication.kt:
package com.example.July30th
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class July30thApplication
fun main(args: Array<String>) {
SpringApplication.run(July30thApplication::class.java, *args)
}
Output:
In second example we used to perform add and display the data.
Example #3
Entities.kt:
package com.example.July30th
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
data class Colors(
@Id
@GeneratedValue
val id: Long = -1,
@Column(name = "colorName")
val colorName: String = "",
){
override fun toString(): String{
return "Color[id=${id}, colorName=${colorName}]"
}
}
ColorController.kt:
package com.example.July30th
import org.springframework.http.ResponseEntity
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
import org.springframework.web.bind.annotation.*
import javax.validation.Valid
import com.example.July30th.ColorRepository
@RestController
@RequestMapping("/color")
class ColorController( val colorService: ColorService, val repo:ColorRepository) {
@PostMapping("/color")
fun addColor(@Valid @RequestBody color:Colors): ResponseEntity<Colors> = colorService.addColor(color)
@GetMapping("/color")
fun getColorsById(@PathVariable(value="id") id: Long): ResponseEntity<Colors> =
colorService.getColorsById(id)
@DeleteMapping("/{id}")
fun deleteColor(@PathVariable(value="id") id: Long):ResponseEntity<Void> = colorService.deleteColors(id)
}
ColorService.kt:
package com.example.July30th
import com.example.July30th.Colors
import com.example.July30th.ColorRepository
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.GetMapping
@Service
class ColorService(private val colorRepository: ColorRepository) {
fun addColor(color: Colors): ResponseEntity<Colors> =
ResponseEntity.ok(colorRepository.save(color))
fun getColorsById(id: Long): ResponseEntity<Colors> =
colorRepository.findById(id).map { color ->
ResponseEntity.ok(color)
}.orElse(ResponseEntity.notFound().build())
fun deleteColors(id: Long): ResponseEntity<Void> =
colorRepository.findById(id).map { color ->
colorRepository.delete(color)
ResponseEntity<Void>(HttpStatus.ACCEPTED)
}.orElse(ResponseEntity.notFound().build())
}
Repositories. kt:
package com. example.July 30th
import org.spring framework.data.repository.CrudRepository
import com. example.July30th.Colors
interface ColorRepository: CrudRepository<Colors, Long>{
}
Output:
In the final example, we additionally performed delete operations.
Conclusion
In kotlin it has many features to perform the operations in the application level. Among those exposed is the framework library that overview and collects all the data using the Exposed framework like database connections it may be of any database tools for performing this operation in the application.
Recommended Articles
This is a guide to Kotlin Exposed. Here we discuss the Introduction, syntax, and working of exposed in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –