Search code examples
grailsgroovygrails-orm

Gorm: object mapping


I have two objects, a CarOffer and a Car. A CarOffer is composed of various attributes, one of which references a Car. In other words, I can have multiple CarOffers, multiple Cars, but there is one and only one Car per CarOffer. A Car can be present in multiple CarOffers. Deleting a CarOffer should not delete the car it references, and deleting a Car should not be possible unless all CarOffers referencing it have also been deleted.

Usually, I would just have added a carId attribute to CarOffer, but from the gorm documentation I feel I should use the power of Gorm to add a Car Object to CarOffer, instead of just its id.

However I'm a bit lost, I feel neither 'belongsTo' nor 'hasOne' really map to what I want.

Besides, how would I go to create a new CarOffer? I would expect to be able to do

new CarOffer(carId: 123).save()

but instead I feel I must do:

new CarOffer(car: Car.get(123)).save()

Does that not create one extra request?


Solution

  • I feel neither 'belongsTo' nor 'hasOne' really map to what I want.

    You don't want belongsTo because that will cause deletes to be cascaded and you said you didn't want that ("Deleting a CarOffer should not delete the car it references").

    You could use a hasOne or not, that will affect which table has the foreign key in it.

    If you don't want to use the carId approach, you can do something like this:

    class CarOffer {
        String attribute1
        int attribute 2
        // etc...
    
        Car car
    }
    
    class Car {
        String attribute1
        // etc...
    
        // There could be, but does not need to be
        // any mention of CarOffer in this class
    }
    

    ...how would I go to create a new CarOffer?

    It depends on details in your app that you haven't mentioned but you can do some thing like this...

    Car c = // ...
    CarOffer co = new CarOffer(attribute1: 'something', attribute2: 2112, car: c)