【问题标题】:Initializing a Date property in beforeInsert fails without exception在 beforeInsert 中初始化 Date 属性无一例外地失败
【发布时间】:2012-03-13 04:01:21
【问题描述】:

我有一个标准的用户类,它是由 Grails 2.0.1 中的 spring-security-core 插件创建的。我通过 mongodb 插件使用 mongodb 进行持久化。

如果我将 Date 属性添加到用户类并将 beforeInsert() 事件处理程序更改为类似的内容

def beforeInsert() {
    userCreated = new Date()
    encodePassword()
}

用户不再被持久化。没有显示异常。它只是默默地失败。 如果我在定义 userCreated 属性时对其进行初始化:

Date userCreated = new Date() 

并从 beforeInsert() 事件处理程序中删除初始化一切正常。 有人对这种行为有解释吗?

顺便说一句:我故意不使用自动时间戳功能,因为我想使用创建日期来加盐密码。如果我通过自动时间戳使用 dateCreated,则在调用 beforeInsert() 事件处理程序之后更新 dateCreated 字段并且密码不再有效。

【问题讨论】:

  • 尝试将 grails.gorm.failOnError 添加到 Config.groovy 并再次运行您的代码。如果模型有任何问题,这应该会显示一个异常。
  • 在 conf/Config.groovy 中添加了 grails.gorm.failOnError = true 行,但没有任何改变......仍然默默地失败......

标签: grails spring-security grails-orm


【解决方案1】:

尝试将 beforeInsert 代码包装到事务中,因为我认为 encodePassword() 方法不是服务方法

【讨论】:

  • 我不确定我是否理解正确。这就是你在说的吗?为方法添加注释? @Transactional def beforeInsert() { created = new Date() encodePassword() }
  • 或者你的意思是使用这样的东西: def beforeInsert() { User.withTransaction{ created = new Date() encodePassword() } } 但是,没有任何运气......仍然一样问题。 encodePassword() 不是服务。只是域类中的一个辅助方法。
  • 我的意思是你最后的评论。所以.. 在 beforeInsert 中,我在自己的项目中使用了 withNewSession {session-> ... }。也许它会帮助你......
  • 感谢您的澄清。我的 beforeInsert 回调现在看起来像这样: def beforeInsert() { User.withNewSession { session -> created = new Date() encodePassword() } } 但是,它仍然默默地失败...只要数据库中没有用户我的事件侦听器中有 created = new Date() 行。如果我删除此行,一切正常。有什么想法可能是错的吗?
  • 奇怪...尝试将“userCreated”重命名为“userDateCreation”。
猜你喜欢
  • 2021-01-22
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多