More Than Five
More Than Five

Reputation: 10419

GORM mappedBy and mapping difference

In the GORM what is the difference between mappedBy and mapping?

static mapping = {
...
}

static mappedBy = {
...
}

Upvotes: 2

Views: 2421

Answers (1)

PhilMr
PhilMr

Reputation: 495

mapping
mapping simply tells GORM to explicitly map one or more Domain properties to a specific database column.

class Person {
   String firstName

   static mapping = {
      table 'people'
      id column: 'person_id'
      firstName column: 'First_Name'
   }
}

in this case for instance I am instructing GORM to map the id attribute to the column person_id of the people table and the firstName property to the First_Name column of the same table.

mappedBy
mappedBy instead let you control unidirectionality or bidirectionality of your classes associations. From Grails documentation:

class Airport {
   static mappedBy = [outgoingFlights: 'departureAirport',
                   incomingFlights: 'destinationAirport']

   static hasMany = [outgoingFlights: Route,
                  incomingFlights: Route]
}

class Route {
    Airport departureAirport
    Airport destinationAirport
}

Airport defines two bidirectional one-to-many associations. If you don't specify mappedBy you would get an error because GORM cannot infer which of the two properties on the other end of the association (either departureAirport or destinationAirport) each one-to-many should be associated with.

enter image description here

In other words it helps you remove the ambiguity that comes from bidirectional associations.

Upvotes: 8

Related Questions