为什么一对一的关系不起作用?

时间:2010-06-13 15:54:16

标签: grails gorm

我正在尝试在两个对象之间创建一个非常简单的关系。任何人都可以解释一下为什么我无法通过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 = {
    }
} 

1 个答案:

答案 0 :(得分:3)

名为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 }