0

I am still learning Grails. I am building up my kickoff project little by little. Please excuse me for so many newbie questions.

The command generate-all creates my book service class. Grails generates the BookService. It looks like this.

import grails.gorm.services.Service
@Service(Book)
interface BookService {
    Book get(Serializable id)
    List<Book> list(Map args)
    Long count()
    void delete(Serializable id)
    Book save(Book book)
}

Grails generates the BookController with a save action that call the service to save my book.

bookService.save(book)

So far so good. I can save without any problem. BUT instead, I replace bookService.save(book) with simply book.save() in the save action. Now, it won't save my book to the database. I also try book.save(flush: true). It won't save the book either.

Do you have any idea why book.save() (with or without flush: true) will not save but bookService.save(book) will save?

I don't know what interface BookService means in Grails. Would you teach me where I can add more methods to the BookService please?

Many Thanks.

tom6502
  • 180
  • 7

1 Answers1

0

Save outside transaction is not allowed. Controllers are not transactional. If you want to save in controller then move the save logic in a transaction, like -

Book.withTransaction { status ->
  ...
}

https://github.com/hibernate/hibernate-orm/blob/5.2/migration-guide.adoc#misc

The best practice is to use the Service layer for all database related activities.

And for about interface Service please have a look at http://gorm.grails.org/latest/hibernate/manual/index.html#dataServices

Grails: How to override generated service method?

Grails 3.3.3 generate-all <domain class> Creates only the Service Interface

MKB
  • 7,587
  • 9
  • 45
  • 71
  • Wow! That is great! I would never find any of these pages since I did not know the Grails terminology. Thanks! – tom6502 Oct 28 '20 at 17:51
  • May I ask you another question? So, generate-all generates a data access service. It is not the same as this service the document from Grails. Correct? https://docs.grails.org/4.0.5/guide/services.html – tom6502 Oct 28 '20 at 20:01
  • Data access services converted to this service for you at compile time by GORM. – MKB Oct 29 '20 at 05:19