Search code examples
grailsgrails3

delete is not working even in service?


I have book domain

package bookfinal

class Book {

    String name
    static constraints = {
    }
}

Book Controller is as follows

package bookfinal

class BookController {

    def bookService

    def destroy(Long id){
        bookService.destroy(id)
        redirect(action:'index')
    }

    def index() {

        [books: Book.findAll()]
    }

    def create(){

    }

    def save(){
        def book = new Book(params)
        book.save()
        redirect(action:'show', id:book.id)
    }

    def edit(Long id){
        [book: Book.get(id)]
    }

    def update(Long id){
        bookService.update(id, params)
        redirect(action:'index')
    }

    def show(Long id){
        [book: Book.get(id)]
    }


}

Service is as follows

package bookfinal

import grails.gorm.transactions.Transactional

@Transactional
class BookService {

    def destroy(Long id) {

        def b = Book.get(id)
        b.delete()

    }


    def update(Long id, params){

        def book = Book.get(id)
        book.properties = params
        book.save()
    }

}

Show page is as follows

<h1> ${book.name} </h1>

<g:link action="edit" id="${book.id}">Edit</g:link>
<g:link action="destroy" id="${book.id}">Delete</g:link>
<g:link action="index">Back</g:link>

Now, when i click on delete it redirects to index but the record isn't deleted. Why is delete not working even within service? I am using Grails 3.3.2 version. When i do delete(flush:true) then it works but i was expecting that just delete() work in service since it is transactional. Am i missing anything? I appreciate any help. Thanks!


Solution

  • It's one of the Grails3 changes. Check official Grails3 docs:

    The save method informs the persistence context that an instance should be saved or updated. The object will not be persisted immediately unless the flush argument is used

    More info:

    In previous versions of GORM the flush mode defaulted to AUTO. With this setting the session would be flushed with or without the presence of a transaction and before every query.

    The frequent flushing of the session before queries can lead to unintended performance consequences if the behaviour of the AUTO is not fully understood by the developer.

    With this in mind COMMIT is the new default flush mode in GORM 6, which will flush the session on transaction commit. You can restore the previous behaviour by configuring the flush mode in your application configuration (for example application.yml):

    hibernate:
        flush:
            mode: AUTO