-
Notifications
You must be signed in to change notification settings - Fork 8
/
AuthorService.kt
39 lines (33 loc) · 1.51 KB
/
AuthorService.kt
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.z.bookbackend.services
import com.z.bookbackend.models.Author
import com.z.bookbackend.util.BasicCrud
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import java.util.*
@Service//declare this class as a Service "Component specialization"
/*injects DAO objects by constructor & implements BasicCrud interface*/
class AuthorService(private val authorDAO: AuthorDAO, private val bookDAO: BookDAO):BasicCrud<String, Author>{
override fun getAll(pageable: Pageable): Page<Author> = authorDAO.findAll(pageable)
override fun getById(id: String): Optional<Author> = authorDAO.findById(id)
override fun insert(obj: Author): Author = authorDAO.insert(obj)
@Throws(Exception::class)
override fun update(obj: Author): Author {
return if(authorDAO.existsById(obj.id)){//check if author exists because the save method will insert a record if does not exists
authorDAO.save(obj).apply { //update author
obj.id?.let { //if does has Id then
bookDAO.saveAll(bookDAO.findByAuthorId(it).map { it.also { it.author=this } })//update all his books
}
}
}else{
throw object : Exception("The author does not exists"){}
}
}
override fun deleteById(id: String): Optional<Author> {
return authorDAO.findById(id).apply {
this.ifPresent {
authorDAO.delete(it)
}
}
}
}