Grails / GORM:org.hibernate.AssertionFailure:xyz中的null id(发生异常后不要刷新Session)

时间:2015-07-11 04:49:32

标签: hibernate grails gorm

我的grails / jaxrs应用程序无法自动保留嵌套对象图,并且想知道我是否可以使用数据模型来使其工作。

资源正确反序列化对象,然后保存父对象(Tauthor),但无法自动保存子对象(Tooks)。子节点具有空id,以及对父节点的空引用。

我可以手动创建子对象,但我正在寻找一种更好的方法来管理它。

域类

class Tauthor {

    String nameShort
    Integer age

    static hasMany = [tooks:Took]

}

class Took {

    String title;

    static belongsTo = [tauthor:Tauthor]
}

资源

@Consumes([MediaType.APPLICATION_JSON, "application/json"])
@Produces([MediaType.APPLICATION_JSON, "application/json"])
@Path('/api/tauthor')
class TauthorResource {

    TauthorService tauthorService

    @POST
    Tauthor create(Tauthor dto) {
      Tauthor created = tauthorService.save(dto)
      if(!created.hasErrors()) {
        return created
      }
    }
}

渴望但服务中断

class TauthorService {

    Tauthor save(Tauthor dto) {
        dto.validate()

        if (dto.hasErrors()) {
            return dto
        }

        return dto.save()
    }
}

工作服务

class TauthorService {

    Tauthor save(Tauthor dto) {
        dto.validate()

        if (dto.hasErrors()) {
            return dto
        }

        // remove tooks, and create them separately
        Set<Took> tooks = []
        tooks += dto.tooks

        tooks.each { took ->
            dto.removeFromTooks(took)
        }

        Tauthor created = dto.save()

        // readd tooks to tauthors
        tooks.each { took->
            took.tauthor = created
            took.save()
        }

        tooks.each { took->
            created.addToTooks(took)
        }
        created.save()

        return created

    }
}

示例JSON

{
   "class":"org.tan.Tauthor",
   "nameShort":"tankak",
   "age":13,
   "tooks":[
      {
         "class":"org.tan.Took",
         "title":"harry"
      },
      {
         "class":"org.tan.Took",
         "title":"potter"
      }
   ]
}

0 个答案:

没有答案