【问题标题】:Would you show me how to save my domain class你能告诉我如何保存我的域类吗
【发布时间】:2020-10-28 06:57:22
【问题描述】:

我还在学习 Grails。我正在一点一点地建立我的启动项目。请原谅我这么多新手问题。

命令 generate-all 创建我的图书服务类。 Grails 生成 BookService。看起来像这样。

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 使用保存操作生成 BookController,该操作调用服务来保存我的书。

bookService.save(book)

到目前为止一切顺利。我可以毫无问题地保存。但是,我在保存操作中将 bookService.save(book) 替换为 book.save() 。现在,它不会将我的书保存到数据库中。我也尝试 book.save(flush: true)。它也不会保存这本书。

你知道为什么 book.save()(有或没有 flush: true)不会保存但 bookService.save(book) 会保存吗?

我不知道 interface BookService 在 Grails 中是什么意思。 请教我在哪里可以向 BookService 添加更多方法?

非常感谢。

【问题讨论】:

    标签: grails


    【解决方案1】:

    不允许保存外部交易。控制器不是事务性的。如果要保存在控制器中,则将保存逻辑移动到事务中,例如 -

    Book.withTransaction { status ->
      ...
    }
    

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

    最佳做法是对所有与数据库相关的活动使用Service 层。

    关于interface Service,请查看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

    【讨论】:

    • 哇!这太棒了!因为我不知道 Grails 术语,所以我永远找不到这些页面。谢谢!
    • 我可以再问你一个问题吗?因此,generate-all 生成了一个数据访问服务。它与来自 Grails 的文档不一样。正确的? docs.grails.org/4.0.5/guide/services.html
    • GORM 在编译时为您转换为该服务的数据访问服务。
    猜你喜欢
    • 2021-03-09
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2021-06-27
    相关资源
    最近更新 更多