Search code examples
hibernategrailsmany-to-manyrelational-databasegrails-orm

How do I model a Student-Class Relationship in grails ORM? Many-to-many relationship


This is what I have

class Student {
     static hasMany = class: Class
     static belongsTo = Class
}

class Class {
     static hasMany = student: Student 
}

I want to prevent any cascade deletion. Incase a class is deleted, the student shouldnt be even though they "belong-to" the Class object.


Solution

  • I'm leaving the original answer below for reference, but I'm pretty sure it was wrong. Per the documentation I linked, "Many-to-many: only saves cascade from the "owner" to the "dependant", not deletes."

    --Original answer below--

    In this case, your Student does not actually 'belongsTo' a class. The purpose of 'belongsTo' is for controlling cascading saves and deletes, and in this case it doesn't sound like you want that.

    http://docs.grails.org/latest/ref/Domain%20Classes/belongsTo.html

    You can have many to many without a belongsTo.

    Also just as a heads up: you're going to confuse yourself by having something called "Class". This will go badly even if it works, which I don't really think it will. That's a reserved word in Java and already exists as a java class.