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.

Let's rename this blog

When I started this blog, I though the name was a good idea - one blog for one purpose. With lots of effort and motivation, I wrote the first entries. But I soon noticed that the topic isn't too interesting: relational databases are supported very well by Grails. Others are supported, but they are not the kind of database Grails was written for. So I stopped writing posts.

Later I added one off-topic post which got the most comments. And I am still doing lots of Grails development and would have lots of ideas to write down ... if I would have more time and the blog another name.

That's why I now change the name some something different. Maybe it will change a cuple of times during the next days - we'll see...

Just for the records: the old name was "Seven Databases used with Grails (in seven Weeks)"

I would like to start the new theme with some database patterns for Grails which I use often...