2014-10-07 62 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