【问题标题】:Grails-null id in com.easytha.Student entry (don't flush the Session after an exception occurs)com.easytha.Student 条目中的 Grails-null id(发生异常后不要刷新 Session)
【发布时间】:2014-01-26 09:38:41
【问题描述】:

我已经看到了几个关于这个问题的帖子,没有一个可以挽救 我的 DomainClass 中有以下内容

def afterInsert() {     
        elasticSearchService.index(this)
}

其中 elasticsaerch 是一项服务,我已将其添加到静态瞬态列表中。好像调用index方法成功后抛出了这个异常

Message: null id in com.easytha.Student entry (don't flush the Session after an exception occurs)

这是索引方法的代码

def  index(object) {
    try {
        if(object==null) {
            throw new NullPointerException()
        }
        if(!(object instanceof Collection || object instanceof Object[])) {
            IndexResponse response = client.prepareIndex(grailsApplication.config.esIndexName, object.getClass().getName(),object.id.toString())
                    .setSource((object as JSON).toString() )
                    .execute().actionGet()
            println "object indexed successfully" 
        }else if(object instanceof Collection || object instanceof Object[]) {
            for (var in object) {
                index(var)
            }
        }
    }catch(e) {
        e.printStackTrace();
    }
}

“对象索引成功”在控制台中打印。

bootstrap.groovy 有以下内容

Student student4 = new Student(firstName:'Sapan',lastName:'Parikh',email:'sapan.parikh@eclinicalworks.com',password:'test123')
    student4.save(failOnError : true)

更新

我尝试了Student.withNewSession { elasticSearchService.index(this) },它奏效了。

【问题讨论】:

  • 你在 Bootstrap.groovy 中做什么?您在这里提供该代码
  • @Motilal 添加了引导代码,这是一个简单的保存操作。也没有验证错误,我通过打印 this.errors 来检查它们
  • 将刷新添加到您的保存 () 并尝试重新启动您的应用 student4.save(flush:true, failOnError : true)
  • @Motilal nope 仍然是同样的错误。
  • This question 可能会给你一些想法。

标签: grails elasticsearch grails-domain-class grails-services


【解决方案1】:

它正在处理一些事情,但可能会将保存转移到在事务中发生:

Student.withTransaction {
  student4.save()
}

当我在服务之外做事情时,我看到这个意外弹出(应该,imo,在服务中)。

总结一些后续讨论:

学生模型保存在整个应用程序中,因此不适合将所有保存转移到服务或包装在事务块中。 OP 指出,将原始的重新索引代码移动到新会话中会在任何地方修复它。

def afterInsert() {     
    elasticSearchService.index(this)

}

【讨论】:

  • 是的,你是对的,这解决了引导问题,但 student.save 遍布整个代码库。我必须在任何地方更改它吗?
  • 它与 Student.withNewSession { elasticSearchService.index(this) } 一起使用
  • 这可能会解决我在一些 GPars 代码中遇到的问题,谢谢!
  • 你想改变你的答案吗,我可以接受。对其他人有帮助吗?
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 2023-04-07
  • 2014-05-12
  • 2014-04-07
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
相关资源
最近更新 更多