1
votes

I have a legacy database with same property to Primary Key and Foreign Key. I'm trying to map it from Grails but I have problems with that. This is my domain class:

class AccommodationPrice {
    Integer id
    Accommodation accommodation

    static mapping = {
         table 'alojamiento_precios'
         id generator: 'assigned', name: accommodation, type: 'integer'
         accommodation column: 'id'
    }
}

This is the database table:

CREATE TABLE alojamiento_precios
(
  id integer NOT NULL,
  CONSTRAINT alojamientoprecios_pkey PRIMARY KEY (id),
  CONSTRAINT "FK alojamiento" FOREIGN KEY (id)
      REFERENCES alojamiento (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

I read this question Grails: Foreign key as primary key? but it didn't work for me: when I use the composite key, grails asks me for accommodation_id, but I don't have this property in my table, because it is id.

1
Wait. Do you want to use the accomodation id as AccomodationPrice's id or do you want a composite key with id/accomodation id? - Tiago Farias
I want to use accommodation id as AccommodationPrice's id. - zot24

1 Answers

0
votes

In case what you want is simply to map an attribute as an id, you can do it like ():

    class AccommodationPrice {

        String price

        long accomodationId

        static mapping = {
             table 'alojamiento_precios'
             id generator: 'assigned', name:'accomodationId'
         version false
        }

        static transients = ['accomodation']

        Accomodation getAccomodation() {
        Accomodation.get(accomodationId)
        }

        void setAccomodation(Accomodation a) {
             accomodationId = a?.id
        }
    }

You don't even need to declare the type you want, GORM assumes the type of your accomodation primary key. You may have problems when using some criteria queries though. But then HQL is straightforward and works ok.

This strategy is known as primary key association and you can find a good discussion about it on gorm in here.

I hope it helps!