Saturday, February 16, 2013

Database-Pattern 1: Property-Group

There are times when you create a complex domain class where you might come up with code like this:

User.groovy
class User {
  String name
  String email
  String addressStreet
  String addressZip
  String addressCity
}

ok. I guess this is obvious - there should be another data type 'Address' to hold the three address properties. Something like

User.groovy
class User {
  String name
  String email
  Address address
}
Address.groovy
class Address {
  String street
  String zip
  String city
}

but isn't this waste? How many users will share the same address? The answer is most of the time zero. So why do we create another domain class for that? Do we need to store the data in another table? It looks cleaner, but IMHO Grails has a more elegant concept for domain classes like that:

User.groovy
class User {
  String name
  String email
  Address address
  static embedded = ['address']
}

class Address {
  String street
  String zip
  String city
}

Notice that this time, we only have one file with two classes. The 'embedded' definition ensures that both classes are stored in one table. Grails calls this 'Composition'

There is only one drawback: the scaffolding does not take the composite properties into account. And the composite properties break the generated create-view.

3 comments:

  1. we can still embed even when separate classes right?

    ReplyDelete
  2. hi. thanks for article There is a way to take in account composite keys in scaffolding ?

    ReplyDelete
    Replies
    1. search for "grails compound key" : http://stackoverflow.com/a/7383118/204769

      Delete