Quick Tip: domain class properties in Grails

Ever wanted to see if a domain class had a many-to-many association in a Grails controller? What about getting a list of persistent properties? In this post, I will outline a quick solution that Jakob Külzer and I figured out for a recent project…

The secret to accessing Grails domain class properties outside of a domain class is to use the DefaultGrailsDomainClass.

Let’s say I have a domain object Foo, In the FooController, I can call

def fooDomain = new DefaultGrailsDomainClass( Foo.class )

then I can call

println “${it.name} ${it.oneToMany}”

Which will show me all the properties for this domain class and whether the result is a one to many association.

You can access the full API here : DefaultGrailsDomainClass

Use carefully!


6 thoughts on “Quick Tip: domain class properties in Grails

  1. Pingback: Ninja Coding Monkey goes Canada » Blog Archive » International Programmers Day

  2. Burt

    Cool stuff. There’s a DefaultGrailsDomainClass registered as a Spring bean for each domain class, so you can save yourself the instantiation by using

    def fooDomain = ctx.getBean(‘FooDomainClass’)

    assuming you have the app context

    or just

    def FooDomainClass

    in a controller or service.

  3. Pingback: Listar las propiedades de un Domain « Tincho in the sky

  4. Tom

    Now it’s even easier, since domain classes get an injected property called ‘domainClass’:
    GrailsDomainClass fooDomain = FooDomainClass.domainClass

  5. orubel

    Tricky to determine the methods from actual properties. Anyone know of an easy way to solve? was looking at isActionMethod but I dont think thats quite right 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s