user742102
user742102

Reputation: 1365

failed to lazily initialize a collection, no session or session was closed

I know this has been asked lot of times and I have read/tried most of the solutions I can ever find. But I can not find the exact solution to my problem. Most of them are calling the save() but I am only getting the list. This is in groovy/grails.

the error "failed to lazily initialize a collection, no session or session was closed" occurs when this code is executed the return caseVisualImpairmentCauses part. When the caseVisualImpairmentCauses contains value, it returns the error "object references an unsaved transient instance - save the transient instance before flushing".

def List<CaseVisualImpairmentCause> bindVisualImpairmentCause(Long visualImpairmentPrimaryCauseId, ArrayList caseVisualImpairmentCausesList,
    String visualImpairmentOtherCause) {
    def caseVisualImpairmentCauses = []

    if (visualImpairmentPrimaryCauseId) {
        def visualImpairmentPrimaryCauseInstance = VisualImpairmentCause.get(visualImpairmentPrimaryCauseId)
        CaseVisualImpairmentCause caseVisualImpairmentPrimaryCause = new CaseVisualImpairmentCause(visualImpairmentCauseIdvisualImpairmentCause: visualImpairmentPrimaryCauseInstance)
        caseVisualImpairmentPrimaryCause.isPrimary = true
        caseVisualImpairmentCauses << caseVisualImpairmentPrimaryCause
    }
    caseVisualImpairmentCausesList.each {
        VisualImpairmentCause visualImpairmentCause = VisualImpairmentCause.get(it as Integer)
        CaseVisualImpairmentCause caseVisualImpairmentCause = new CaseVisualImpairmentCause(visualImpairmentCauseIdvisualImpairmentCause: visualImpairmentCause)
        if (it.equals('5')) {
            caseVisualImpairmentCause.caseVisualImpairmentCauseOther = visualImpairmentOtherCause
        }
        caseVisualImpairmentCauses.add(caseVisualImpairmentCause)
    }
    return caseVisualImpairmentCauses
}

the one calling that is

    obpCaseInstance.visualImpairmentCauses = caseService.bindVisualImpairmentCause(visualImpairmentPrimaryCauseId, listOfCaseVisualImpairmentCauses, visualImpairmentOtherCause)

any idea why this error happens?

Upvotes: 1

Views: 3845

Answers (1)

user742102
user742102

Reputation: 1365

I was able to solve this by changing all findbyId(), .get() and getbyId() into .read(). It appears that the methods(find, get) are already flushing and as good as calling .save(). I also took out all methods fetching data (methods that cant be replaced by .read() like findBYOtherproperty) being called from another service and put it in the same method instead. This made the error go away without me forcing to save the object first before leaving the service.

Upvotes: 2

Related Questions