2014-10-07 58 views
0

我想对域关联进行反射来为REST式WS(脚手架)自动生成JSON/XML格式的类描述符文件。对于HasOne(假设是双向的),我试图使用Association对象中的referencedPropertyName来显示反向键(这是WS必须显示的唯一信息)。Grails hasOne关系真的是双向的吗?

不过,我发现hasOne关联没有正确初始化。

以下是我使用Grails 2.3.7进行的测试。

我的领域是:

class House { 

    Long number 
    Integer inhabitants 

    static hasOne = [ roof: Roof ] 
    static hasMany = [ doors: Door ] 

    static constraints = { 
     roof nullable: true, unique: true 
    } 
} 

class Roof { 

    String color 
    House house 

    static constraints = { 
    } 
} 

然后:

import org.grails.datastore.mapping.model.types.Association 
import org.junit.Test 

import spock.lang.* 
import test.House 
class AssociationsSpec { 
    @Test 
    void "test something"() { 
     House.gormPersistentEntity.associations.each { Association association -> 
      String key = association.name 
      println association.properties 
      assert association.bidirectional 
     } 
    } 
} 

该测试失败:

Assertion failed: 
assert association.bidirectional 
     |   | 
     |   false 
     test.House->roof 
    at test.AssociationsSpec$_test_something_closure1.doCall(AssociationsSpec.groovy:26) 
    at test.AssociationsSpec.test something(AssociationsSpec.groovy:23) 

附加信息(的println association.properties):

[list:false, type:interface java.util.Set, owner:org.[email protected]149a797, class:class org.codehaus.groovy.grails.domain.GrailsDomainClassPersistentEntity$5, cascadeOperations:[ALL], inverseSide:test.Door->house, capitilizedName:Doors, bidirectional:true, referencedPropertyName:house, associatedEntity:org.[email protected]99a9c3, mapping:null, circular:false, owningSide:true, name:doors, fetchStrategy:EAGER] 

[capitilizedName:Roof, bidirectional:false, referencedPropertyName:null, circular:false, owningSide:true, name:roof, list:false, type:class test.Roof, owner:org.[email protected]149a797, class:class org.codehaus.groovy.grails.domain.GrailsDomainClassPersistentEntity$4, cascadeOperations:[ALL], inverseSide:null, associatedEntity:org.[email protected]16289cc, mapping:null, foreignKeyInChild:true, fetchStrategy:EAGER] 

谢谢

回答

3

为了使这种双向的,你需要添加static belongsTo = [house: House]Roof域删除您House house财产。

您可以在documentation中阅读有关belongsTo属性的更多信息。

+0

试过但结果相同。根据GORM,如果事实上一直是双向的。我也尝试作为房屋{门门}和课堂门{静态belongsTo = [房子:房子]}中的一个属性,它们都不起作用。 – user2108278 2014-10-08 07:39:26