FrancescoDS
FrancescoDS

Reputation: 995

grails: how to implement a "zero-to-one" relationship

I need to implement a "zero-to-one" relationship. In particular, I have two classes: Event and Patient; I want that, when I create an event, is possible to choose or not a patient. I've found something like the following: in Event class, add a field Patient, with a nullable constraint, but I think that, when I delete the Patient instance, the related events will be not automatically deleted in cascade... Is there a way to do it automatically? Or do I need to perform it manually?

EDIT: following your suggestion, I've created a method that deletes events of the patient as follows:

 def beforeDelete() {
    new EventController().deleteEventsOfPatient(this)        
}

def deleteEventsOfPatient(Patient patient)
{
    def eventsOfPatient = Event.findAllByPatient(patient)
    for(int i = 0; i < eventsOfPatient.size(); i++)
    {
        if (!eventsOfPatient[i].delete(flush: true)) {
            flash.message = "error in delete event of patient";
        }

    }

}

but it raises the following exception:

Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

Upvotes: 0

Views: 414

Answers (1)

Grooveek
Grooveek

Reputation: 10094

Have a look at Grails doc paragraph titled 'Events and Auto Timestamping'

You have a beforeDelete event which could be used to delete cleanly your Patient if one exists, something like the following :

class Patient{

    def beforeDelete() {
         deleteEventsOfPatient()        
    }

    def deleteEventsOfPatient(){
         def eventsOfPatient = Event.findAllByPatient(this)
         for(int i = 0; i < eventsOfPatient.size(); i++){
             eventsOfPatient[i].delete() 
         }       
    }
}

Upvotes: 1

Related Questions