开发者

Why One-to-one relationship dosen't work?

开发者 https://www.devze.com 2023-01-03 20:05 出处:网络
I\'m trying to create a very simple relationship between two objects. Can anybody explain me why I can\'t find the Company object via findBy method?

I'm trying to create a very simple relationship between two objects. Can anybody explain me why I can't find the Company object via findBy method?

class Company {
    String name
    String desc
    City city
    static constraints = {
        city(unique: true)
    }
}
class City {
    String name
    static constraints = {
    }
}
class BootStrap {
    def init = { servletContex开发者_Go百科t ->
        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 = {
    }
} 


A field called desc conflicts with the database keyword for descending sort. Per default a field is nullable:false in Grails. So first rename that field to for example description and then provide one or mark that field as nullable:true in your 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()
    assert Company.findByName('company') != null
  }    
} 

Remember that you can always check for the errors that prevent Grails from saving your objects to the database easily:

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

精彩评论

暂无评论...
验证码 换一张
取 消