【问题标题】:Why One-to-one relationship dosen't work?为什么一对一的关系不起作用?
【发布时间】:2010-06-13 15:54:16
【问题描述】:

我试图在两个对象之间创建一个非常简单的关系。谁能解释一下为什么我无法通过 findBy 方法找到 Company 对象?

class Company {
    String name
    String desc
    City city
    static constraints = {
        city(unique: true)
    }
}
class City {
    String name
    static constraints = {
    }
}
class BootStrap {
    def init = { servletContext ->
        new City(name: 'Tokyo').save()
        new City(name: 'New York').save()

        new Company(name: 'company', city: City.findByName('New York')).save()

        def c = Company.findByName('company') // Why c=null????!
    }
    def destroy = {
    }
} 

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    名为desc 的字段与降序排序的数据库关键字冲突。默认情况下,Grails 中的字段是nullable:false。因此,首先将该字段重命名为 description,然后在您的约束中提供一个或将该字段标记为 nullable:true

    class BootStrap {
      def init = { servletContext ->
        new City(name: 'Tokyo').save()
        new City(name: 'New York').save()
        new Company(name: 'company', city: City.findByName("New York")).save()
        assert Company.findByName('company') != null
      }    
    } 
    

    请记住,您始终可以检查阻止 Grails 轻松将对象保存到数据库的错误:

    def invalidCompany = new Company() // missing required name property
    if (!invalidCompany.validate())
        invalidCompany.errors.each { println it }
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多