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.
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