Skip to content

Commit 2c906a9

Browse files
committed
Fixed OneToOne and OneToMany, so that the mapped entities are not deleted, Used @CreationTimestamp and @UpdateTimestamp to update the creation and update times automatically. Return Kotlin Triple in BookService.kt to return a Triple <>
1 parent 3ddf5f3 commit 2c906a9

File tree

6 files changed

+79
-12
lines changed

6 files changed

+79
-12
lines changed

JPATableJoins/build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ plugins {
88
kotlin("plugin.jpa") version "1.4.30"
99
}
1010

11-
group = "com.oreilly"
11+
group = "com.hello"
1212
version = "0.0.1-SNAPSHOT"
1313
java.sourceCompatibility = JavaVersion.VERSION_11
1414

JPATableJoins/src/main/kotlin/com/hello/bookinventory/controller/BookController.kt

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import org.apache.logging.log4j.LogManager
77
import org.springframework.beans.factory.annotation.Autowired
88
import org.springframework.web.bind.annotation.RequestMapping
99
import org.springframework.web.bind.annotation.RestController
10+
import kotlin.Triple as KotlinTriple
1011

1112
@RestController
1213
class BookController {
@@ -43,14 +44,24 @@ class BookController {
4344
return outputString
4445
}
4546

47+
//curl http://localhost:8080/deleteBook
48+
// Deletes a random book from the book table
4649
@RequestMapping ("/deleteBook")
4750
fun deleteBook () : String {
48-
if (bookService.deleteBook ())
51+
val returnTriple = bookService.deleteBook ()
52+
if (returnTriple.first == true)
4953
{
50-
return "Book Deleted"
54+
return "Book ${returnTriple.second} with title ${returnTriple.third} Deleted"
5155
}
5256
else {
5357
return "Book could not be deleted"
5458
}
5559
}
60+
61+
//curl http://localhost:8080/updateBook
62+
// Updates the title of the book from X to X[Updated]. The timestamp should also be updated.
63+
@RequestMapping("/updateBook")
64+
fun updateBook (): String {
65+
return bookService.updateBook()
66+
}
5667
}

JPATableJoins/src/main/kotlin/com/hello/bookinventory/dao/BookRepository.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ import org.springframework.stereotype.Repository
66

77
@Repository
88
interface BookRepository : JpaRepository <Book, Long> {
9+
910
}

JPATableJoins/src/main/kotlin/com/hello/bookinventory/model/Author.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ data class Author (
1010

1111
var name : String = "",
1212

13-
@OneToMany(cascade = arrayOf(CascadeType.ALL), mappedBy = "author", orphanRemoval = true)
13+
@OneToMany(cascade = arrayOf(CascadeType.ALL), mappedBy = "author", orphanRemoval = false)
1414
var bookList : List<Book> = mutableListOf()
1515
){
1616
override fun toString(): String {
Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,33 @@
11
package com.hello.bookinventory.model
22

3+
import org.hibernate.annotations.CreationTimestamp
4+
import org.hibernate.annotations.UpdateTimestamp
5+
import java.util.*
36
import javax.persistence.*
47

58
@Entity
69
data class Book(
710
@Id
8-
@GeneratedValue(strategy=GenerationType.IDENTITY)
9-
var id : Long = 0,
11+
@GeneratedValue(strategy = GenerationType.IDENTITY)
12+
var id: Long = 0,
1013

1114
var title: String = "",
1215

13-
@OneToOne(cascade = arrayOf(CascadeType.ALL))
16+
@OneToOne(orphanRemoval = false)
1417
@JoinColumn(name = "aid")
15-
var author : Author? = null
18+
val author: Author? = null,
19+
20+
@CreationTimestamp
21+
@Temporal(TemporalType.TIMESTAMP)
22+
var createdDate: Date? = null,
23+
24+
@UpdateTimestamp
25+
@Temporal(TemporalType.TIMESTAMP)
26+
var modifiedDate: Date? = null
1627
) {
1728
override fun toString(): String {
1829
return title
1930
}
31+
32+
2033
}

JPATableJoins/src/main/kotlin/com/hello/bookinventory/service/BookService.kt

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import com.hello.bookinventory.model.Book
77
import org.apache.logging.log4j.LogManager
88
import org.springframework.beans.factory.annotation.Autowired
99
import org.springframework.stereotype.Service
10+
import java.util.*
1011
import kotlin.random.Random
12+
import kotlin.Triple as KotlinTriple
1113

1214
@Service
1315
class BookService {
@@ -43,15 +45,55 @@ class BookService {
4345

4446
}
4547

46-
fun deleteBook () : Boolean {
48+
fun deleteBook () : KotlinTriple<Boolean, Long, String> {
4749
val bookCount = bookRepository.count()
48-
val bookToDelete : Long = Random.nextLong(0, bookCount -1)
50+
val bookToDelete : Long = Random.nextLong(1, bookCount)
4951
logger.info ("Will attempt to delete book # $bookToDelete")
5052
if (bookRepository.existsById(bookToDelete))
5153
{
52-
bookRepository.deleteById(bookToDelete)
54+
val book = bookRepository.findById(bookToDelete)
55+
var title : String = ""
56+
if (book.isPresent())
57+
title = book.get().title
58+
logger.info ("Title of book to be deleted : ${title}")
59+
var status : Boolean = true
60+
try {
61+
bookRepository.deleteById(bookToDelete)
62+
}
63+
catch (e: Exception)
64+
{
65+
logger.error("Unable to delete book # $bookToDelete, with title ${title} .")
66+
logger.error ("Exception thrown. ${e.message}")
67+
status = false
68+
}
69+
if (status == true)
70+
return KotlinTriple(true, second = bookToDelete, third = title)
5371
}
54-
return !(bookRepository.existsById(bookToDelete))
72+
return KotlinTriple(false, second = 0L, third = "null")
73+
}
74+
75+
76+
fun updateBook () : String {
77+
val bookCount = bookRepository.count()
78+
// var bookExists : Boolean = true
79+
var i : Long = 1
80+
while (!bookRepository.existsById(i) && i <= bookCount ){
81+
i++
82+
logger.info ("No book found with id # $i .")
83+
84+
}
85+
if (i <= bookCount && bookRepository.existsById(i)){
86+
var book : Book = bookRepository.getOne(i)
87+
book.title = book.title + "[Updated]"
88+
var savedBook : Book = bookRepository.save(book)
89+
return ("Title was updated to ${savedBook.title}")
90+
}
91+
else {
92+
return ("Title was not updated")
93+
}
94+
95+
96+
5597
}
5698

5799
fun findAllAuthors () : List <Author> {

0 commit comments

Comments
 (0)