2013-02-26 6 views
2

현재 프로젝트에서 일대 다 관계를 유지할 수 없습니다. 관계의 양면이 저장됩니다 - 단지 둘 사이의 링크가 누락됩니다. 내 두 도메인 사이일대 다 관계를 유지할 수 없습니다.

한 일대 다 관계는 다음과 같습니다

class Parent { 
    String name 
    ... 

    static hasMany = [childs: Child] 

    Parent() {} 

    Parent(SomeOtherClass obj) { 
     this.properties = obj.properties 
    } 
} 

class Child { 
    int code 
    String description  
} 

나는 ParentService 내에서 내 Parent 인스턴스를 만드는거야 :

public Boolean createParents(List parentIds) { 
    boolean savedSuccessfully = true 
    Parent.withTransaction {status -> 
     parentIds.each { parentIdString -> 
      if (parentIdString && parentIdString.isInteger()) { 
       int parentId = parentIdString.toInteger() 

       def parentInstance = new Parent(someOtherService.getExternalParentObj(parentId)) 

       someOtherService.getExternalChilds(parentId).each { entry -> 
        parentInstance.addToChilds(Child.findOrSaveWhere(code: entry.key, description: entry.value)) 
       } 

       if(!parentInstance.save()) { 
        status.setRollbackOnly() 
        savedSuccessfully = false 
       } 
      } 
     } 
    } 

    return savedSuccessfully 
} 

모두의 Parent 인스턴스 및 Child 인스턴스가 생성되어 성공적으로 저장됩니다. 부모와 자식 간의 연결 고리가 없습니다. 각 Parent 인스턴스의 childs 속성은 빈 목록입니다.

여기에 무엇이 잘못되었는지 알지 못합니다. 왜 관계가 유지되지 않습니까? 어떤 아이디어?

나는 모든 Parent 인스턴스를 생성 한 후 childs 목록의 존재를 테스트하기 위해 ParentService에 대한 통합 테스트를 추가 한

업데이트 : 예기치 않게

... 
assert parentService.createParents(["123","234","356"]) == true 
def parent = Parent.get(1) 
assert parent.childs.size() > 0 
... 

- 통과 시험.

+0

Grails가 부모, 자식 및 parent_child 테이블을 올바르게 만들 수 있는지 확인할 수 있습니까 – uchamp

+0

예 - 모든 테이블이 올바르게 생성되었습니다. _parent_-table 및 _child_-table이 채워집니다. 그냥 조인 테이블 _parent_child_가 비어 있습니다 ... – aiolos

+0

ParentService 및 someOtherService의 트랜잭션 속성은 무엇입니까? 다른 서비스를 호출하기 전에 부모 인스턴스를 저장/비우는 것을 시도해 보았습니까? – codelark

답변

0

오류의 원인을 찾았습니다.

일부는 entry.value입니다. null입니다. 왜 내가 디버깅하는 동안 그것을 보지 못했는지 모르겠다.

entry.valuenull이 아닌 경우에만 Child.findOrSaveWhere()을 사용합니다.

전체 parentInstance.save()이 완전히 통과하거나 완전히 실패 할 것으로 예상 했었습니다. 여전히 조인 테이블이 오류를주지 않고 채워지지 않는 이유를 이해하지 못합니다.

+0

'failOnError : true' 인수를 save()에 추가하면 해당 동작이 발생할 수 있습니다. –

관련 문제