miyav miyav
miyav miyav

Reputation: 368

What is correct approach of deleting a row from table in Kotlin(Springboot) with JpaRepository from Spring?

So I'm learning Kotlin and learning how to make it look clean with Spring.

Lets say i have a repository for user Entity:

@Repository
interface UserRepository : JpaRepository<User, Long>

Then i want to delete the user by it's id fristly i did something like that:

@DeleteMapping("/{id}")
fun deleteById(@PathVariable(value = "id") id: Long): ResponseEntity<Void> {
    return t.findById(id).map {
        t.delete(it)
        ResponseEntity<Void>(HttpStatus.OK)
    }.orElse(ResponseEntity.notFound().build())
}

Where t was UserRepository and it was working just fine and looked clean.

But then I wanted to get retrieving object from database logic outside of the controller so I made a service.

How do I go about deleting an object through service I made something like this in the Service class:

fun deleteById(id: Long): Boolean = t.findById(id).map {
    t.delete(it)
    true
}.orElse(false)

Where t is the Repository, then in my Controller class I made adjustments like so:

@DeleteMapping("/{id}")
fun deleteById(@PathVariable(value = "id") id: Long): ResponseEntity<Void> = if (t.deleteById(id)) ResponseEntity<Void>(HttpStatus.OK) else ResponseEntity.notFound().build()

Where t is the service, but it looks very unclean. So how do i go about making Additional layer like the Service here and making the code more clean?

Upvotes: 0

Views: 1103

Answers (1)

mightyWOZ
mightyWOZ

Reputation: 8335

Your code is already very short and the possibility of size reduction is very thin, but I guess you can still do following

In your service

// use JpaRepository's (existsById) which return a boolean
fun deleteById(id: Long) = if(t.existsById(id)) {t.deleteById(id); true} else false

and in your controller

@DeleteMapping("/{id}")
fun deleteById(@PathVariable(value = "id") id: Long) = if (t.deleteById(id)) ResponseEntity<HttpStatus>(HttpStatus.OK) else ResponseEntity<HttpStatus)(HttpStatus.NOT_FOUND)

Important: Please note that in general you should write code which is easily understandable and managable by others, if someone had to waste 15 mins understanding a simple if statement just because you made it a one liner then that is not very good programming.

As a great programmer once said

Every function should be made as small as possible, but not smaller

Upvotes: 1

Related Questions