【问题标题】:Grails doesn't save domain's fieldGrails 不保存域的字段
【发布时间】:2018-05-16 17:36:02
【问题描述】:

我有两个域类

class Country {
     ... // some fields, including other domains
}

class City {
     ... // some fields, including other domains
     Country itsCountry
}

我的一种服务方法在这里:

City createCity(String name, Country country) {
    // country is existing and loaded in the controller's layer and passed here
    City city = new City()
    city.itsCountry = country // it is not persisted
    city.save('flush':true)
}

问题是在数据库中城市的国家为空。 当然,我把例子简化了,真的是更复杂。 (不幸的是,一些重要的细节可能会丢失,我希望如果你遇到这个问题,你会分享原因)

我做了什么没有成功:

  1. 玩 Country,通过服务方法中的 id 获取它,在保存 City 对象之前保存并刷新它
  2. 使 itsCountry 字段不可为空。所以我从数据库中得到了一个例外,这个字段不能为空。

我觉得这一定是一件微不足道的事情。可能是什么原因?

【问题讨论】:

  • 你的服务是@Transactional吗?
  • 是的。它没有这样的注解,但默认情况下它必须是事务性的。 (没有“静态事务=假”)
  • 什么版本的 Grails?从 Grails 3 的某个地方开始,默认情况下服务是非事务性的,static transactional 已被删除。
  • 您是否尝试过 if(city.validate()){city.save(flush:true)}else{...} 来查看城市对象是否经过验证?在调试器中,您还可以访问城市对象的验证错误。
  • 你使用的是什么版本的 Grails 和 Gorm?

标签: grails grails-orm


【解决方案1】:

在 Grails 中,我们已经可以在 params 中获取国家/地区 ID。对。 例如,params?.countryId。

如果是国家表的新记录,则首先为国家创建新对象并分配到城市对象中。

例如,

Country country = new Country()//for new record
country.name=params?.countryName
City city=new City()
city.itsCountry = country 
city.save('flush':true)

如果表中已有国家/地区记录,则使用 get 方法获取对象并将其分配给城市。

例如,

Country country=Country.get(Long.valueOf(params?.countryId))
city.itsCountry = country 
city.save('flush':true)

希望对你有所帮助。如果有任何疑问,请联系我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-27
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多