【问题标题】:grails hasMany of jodatime Instantsgrails hasMany of jodatime Instants
【发布时间】:2013-02-09 07:31:54
【问题描述】:

如何解决http://jira.grails.org/browse/GPJODATIME-28 的问题,它会阻止域类具有任何扩展类型的 hasMany? 我正在考虑将整个应用程序切换为保留从 BigDecimal 派生的自定义 UserType 用于 posix 纪元日期。看起来就像是核桃的锤子。我可以采取其他方法吗?

import org.joda.time.Instant    
class Foo {    
    Instant birthday 

    Set favoriteDays = []

    static hasMany = [
        favoriteDays : Instant
    ]

    static constraints = {
    }

}

【问题讨论】:

    标签: grails groovy jodatime


    【解决方案1】:

    希望我没有遗漏你的问题,但我已经做了这样的事情:

    创建一个名为MyInstant 的类并在hasMany 中使用它

    import org.joda.time.Instant   
    class MyInstant {
        Instant myInstant
        //anything else you might need
    }
    
    class Foo {
        MyInstant birthday
    
        Set favoriteDays = []
        static hasMany = [favoriteDays: MyInstant]
    }
    

    我已经在FooController 中测试过这个:

    import org.joda.time.Instant
    class FooController {
       def save() {
          def fooInstance = new Foo(params)
            .addToFavoriteDays(new MyInstant(myInstant: new Instant()))
            .addToFavoriteDays(new MyInstant(myInstant: new Instant()))
            .addToFavoriteDays(new MyInstant(myInstant: new Instant()))
    
            if (!fooInstance.save(flush: true)) {
              render(view: "create", model: [fooInstance: fooInstance])
              return
            }
    
            flash.message = message(code: 'default.created.message', args: [message(code: 'foo.label', default: Foo'), fooInstance.id])
            redirect(action: "show", id: fooInstance.id)
        }
    }
    

    一切都会正确保存,然后show 操作会显示所有瞬间的新 Foo。我已经在 H2 和 MySql 上对此进行了测试。

    【讨论】:

    • 谢谢。不幸的是(在 Grails 2.2.0 上)仍然抛出失败;嵌套异常是 org.hibernate.MappingException:域 [Foo] 引用 [ginstant.MyInstant] 上的列 [favorite_days_my_instant] 缺少类型或列。 @Type 注释会有帮助吗?
    • 你试过干净并重新编译吗?我也在使用 2.2.0,我只是测试了一些,这在插入/检索数据的过程中一直有效。在我的Foo 控制器中,我能够创建fooInstance 并将三个MyInstant 对象添加到favoriteDays。我将更新答案以显示这一点。
    • 是的,试过了。我一定是在做别的蠢事。您的 MyInstant.groovy 是否在 ./src/groovy 中?没有 ./grails-app/conf 更改?无法确定类型:MyInstant,在表:foo,列:[org.hibernate.mapping.Column(birthday)]
    • MyInstant 是与 Foo 相同的包中的常规 Grails 域类 - 这可能是您收到错误的原因,因为它不会在 src/groovy 中持续存在。除了 BuildConfig.groovy 之外,没有对任何 conf 文件进行更改以包含 JodaTime。然后完全如图所示创建域,生成控制器/视图并将FooController.groovy 修改为完全如图所示。
    • 你的明星!我不明白 MyInstant 是一个域类。将其移出 ./src/groovy/ 和 viola!
    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多