A guide to mapping databases in Grails with GORM (Dave Cherry)

, June 30th, 2008

Original Source

Dave Cherry has written a GORM guide.

GORM is the data abstraction layer that is used to map domain objects to database tables in Grails. Although GORM can be used outside of Grails, we do not discuss that here, we assume that you are using Grails. In fact we assume you are using V1.0 of Grails.

Grails gets you started quickly, when you create a new project, setting up the database for development should not be required, this is because Grails creates a default datasource that uses an in-memory database.

Unlike Ruby on Rails, GORM starts with the definition of a POGO (groovy object). This object is then used as the template to build the table on the database. Although this can be changed, it is by convention the default way. This article assumes that you are familiar with Grails, and have already created a test project that can be used for this article.

Though GORM depends on some bootstrap code done by Grails core, you can pretty much use it outside of Grails, as Jeremie Wilden shows at Using GORM in a Desktop Application. Dave takes care to point out a crucial difference from RoR: domain models are the primary building blocks in Grails, not the database. These means you are free to model your domain without being restricted by a particular database schema. Usually what happens with a brand new Grails application the database will follow the domain. Then again, because Grails follows the Convention over Configuration paradigm but doesn’t dismiss configuration, you’ll be able to map a legacy database schema to a freshly designed domain. This means you do not have to throw away your current web application in order to take advantage of Grails.

Dave outlines the basics of a domain model, how to map domain constraints which will be reused on views and database schema generation. He also demonstrates two of the three supported relationship mappings

  • one to many
  • many to one

Leaving the many-to-many relationship without example because of the following

If you’ve used Hibernate before, you may be used to mapping many-to-many tables in an invisible way, at the moment GORM does not provide this. Instead the join table must be included in your domain model; then you use the many-to-one and one-to-many support we’ve already seen.

For example if added a ‘Keywords’ object that linked to many Books, and each Books could have many Keywords, we would create a new domain object something like KeywordBookLink that had a one-to-one link with both Keyword and Book. In addition it would be wise to make either Book or Keyword the owner of the link object.

Though it looks like a limitation of Grails/GORM, Graeme Rocher and Dierk König have said before that an explicit joint table is in fact a good idea. Once you reflect on why you need it you may discover additional properties that can be applied to the relationship itself that do not belong to either side per se.

Other topics discussed in the article are

  • basic CRUD operations
  • dynamic listings
  • dynamic finders

the article is not a full description of what you can accomplish with GORM, but it is a very good read for those wanting to learn one of the most powerful tools in the Grails toolbox.

Tags: ,

Sparkline Grails Plugin (Seymour Cakes)

, June 30th, 2008

Seymour Cakes just released the first version of the Sparkline plugin for Grails [Sparkline@Wikipedia]. Here is a sample of what It can do

This is the second Grails plugin based on GraphicsBuilder, a Java2D Groovy builder. It is interesting to note that this plugin bundles its own controller to do the work. It doesn’t cache the resulting images (neither odes the J2D plugin) for the time being, here is hoping both plugins provide a caching mechanism in their next release.

Tags: ,

Glassfish v2/v3 Plugins for Grails (Martin Grebac)

, June 25th, 2008

We have learned from The Aquarium that Martin Grebac posted information on Glassfish v2/v3 plugins for Grails here and here . Sun demonstrated both JRoR and Grails applications running on Glassfish during the first technical keynote (Tuesday). Befroe these plugins were available you had to package your Grails application into a war in order to run it inside Glassfish, now you are able to run your application with an embedded Glassfish instance, same way as it is done with the default embedded Jetty server.

Tags: ,

Groovy / Grails Added into Standard NetBeans Distribution (Roman Strobl)

, June 25th, 2008

Original Source

Roman recently announced that Groovy/Grails support will be available in NetBeans 6.5, but you can try it out today with a nightly build. We have know for a few months ago that Sun was working on Groovy/Grails support and that you could test those features by downloading the development version of NetBeans 6.1 and beyond, which is why these news is a refreshing one, no need to mess around with bleeding edge versions. Milestone 1 of NetBeans 6.5 looks to be released pretty soon so stay tuned at http://www.netbeans.org.

Granted, NetBeans may not be the dominant IDE in the market, but  it is really good to see that it is also providing official support for Groovy and Grails.

Tags: ,

Grails UrlMappings (Ryan Headley)

, June 23rd, 2008

Original Source

Ryan Headley writes about his recent experience with Grails UrlMappings. Grails follows the Convention over Configuration paradigm (as you probably know by now), but that doesn’t mean it will throw away configuration out of the window. Ryan describes a scenario where he would like to reuse an existing controller for two different URLs. If Grails were to follow the CoC paradigm blindly he would surely have had to copy the first controller in order to get the url mappings right.

I [Ryan] am using Grails on one of my current projects in which end-users can enroll in a couple of “different” programs offered by my client.  Behind the scenes, these programs are identical except for the name.  However, the look and feel of the enrollment process will have subtle difference based upon the program that the end-user is enrolling in.

Since the code and the majority of the views are exactly the same, I want to use one controller and just hold the program name in session and refer to it when I need to specify something about that particular program.  Sounds easy enough right?  Well, it is easy UNLESS you want to maintain completely separate URLs for the process.  My client is very interested in tracking this sort of information in Google Analytics and for some reason the urchin tracker isn’t producing the desired results.

Originally, I was giving two possible entry points into this enrollment process, one for each program, but once inside, everything was referring to the same controller.  So how then do I maintain two separate url schemas and still use the same backend controller?  The answer:  UrlMappings.groovy

So how did he do it? After searching around for info and some trial and error he ended with something like this

class UrlMappings {
static mappings = {
“/product2/$action?/$id?” {
controller = “product1″
constraints {
action(matches:”apply|qualify|thankyou”)
}
}
}
}

Which means that any action that matches “apply”, ‘qualify” or “thankyou” called on an url that contains “/product2″ will be actually handled by the controller mapped by “/product1″. In his own words:

This mapping takes all requests for product2 controller and refers it behind the scenes to the product1 controller/action.  The kicker here is the “action(matches:…)” line.  If we request /product1/somethingelse, this mapping won’t match.  (There are certain situations in my project that we had to have some other actions on product2’s controller that product1 didn’t have.  In this case, I created the product2 controller and just added that action.)  If the action “matches” the mapping takes over and uses product1/action behind the scenes while the URL still reads /product2.  Nifty!!  (NOTE:  Take note of the trailing “?” in the mapping url.  It signifies it as an optional parameter.  If I were to put a question mark after the action, everything under product2 would map to product1 which may not be desirable, and for me, it wasn’t).

A Gotcha – One thing I ran into however, was that once I added this mapping, I noticed that the links in my product1 views started pointing to product2’s controller which wasn’t making sense.  So I added another mapping pointing /product1 to its own controller which remedied the problem.  I’m sure if I think about it long and hard enough, I’ll figure out why that was needed, but perhaps that’s for another entry.

In closing, I’m finding that the more I ask of Grails, the more pleased I am with the answers it provides.  It took me a while to get the mappings to work quite right, but once I did it worked like a charm.  Perhaps there are better ways to skin this cat, but this solution worked for me and took very little “coding/configuration” to get the desired result.

You may find more info on URLMappings at the Grails Documentation Site.

Tags: ,

State Diagram to Grails Webflow (grassr.com)

June 23rd, 2008

The folks at grassr.com have posted an introductory article on Grails and Webflow.

So this next look into grails development is meant to help people get to grips with webflows; to explain how to go from a conceptual diagram to real groovy code. So lets begin with a little introduction of the different types of state grails provides us with to build our webflows.

View State
A state of the webflow which just displays a page to the end user.

Action State
An action state has no view but performs some kind of action, effectively it is a code block that gets executed.

Action/View State
Somewhere in between the previously mentioned 2 is the action view state, which renders a view, but can also execute an action prior to moving onto the next state. This will be explained in greater detail below.

So using these types of state we are going to build this state diagram in groovy

State Diagram

The article continues by explaining each step as laid out in the diagram, pointing out default values and settings available through conventions, dispelling any gotchas that may hinder your progress in this scenario. This article is actually linked to a previous one titled Grails Gotchas, where they explain some issues you must take into account when creating webflows in Grails, issues like

Pageflows names have to be unique: give your pageflow unique names, you can always map them to a nicer url using the URLMapping configuration.

In pageflow actions you must use a transaction to perform a delete operation: wrap any calls to delete in a transaction

XML Library Problems: replace the packaged xml-apis.jar and xercesImpl.jar in the <grails_dist>/lib directory and then clean out my whole project and rebuild.

The Hibernate Context: the major problem they wer having is the security framework they were using (acegi) was loading the object in a different context to that of their main application. Which meant when they tried to load collections of a user which desirably would be lazy loaded they were receiving exceptions from hibernate.Their solution was to just store the username as the principal in the session object and rely on the hibernate caching mechanism to stop this from hitting the database every time.

Read the while article at State Diagram to Grails Webflow.

Tags:

Grails Podcast Episode 59: Newscast for June 21, 2008 (Sven Haiges & Glen Smith)

, June 21st, 2008

Tags: ,

JRuby on Rails Good or Bad for Java? (James Ervin)

, June 19th, 2008

Original Source

James Ervin writes:

I am going to apologize for the incendiary title. I think the work the JRuby team has been doing at Sun, particularly with enhancing the JVM for dynamic languages, is great and a service to the entire Java community. The real point of this post is a question to Sun and the rest of the Java community. What is the question? Simple. Y’all why all the emphasis on JRuby and JRuby on Rails and not an equivalent amount of love (read: attention/resources ) to the Groovy/Grails platform? I am combining consideration of both Ruby and Groovy with their equivalent Web frameworks RoR and Grails since they really are the killer apps (read: primary motivation for developers to try them) for both languages at this time.

So why all the attention at Sun to JRuby? Well I think there is probably a mentality at Sun to think they need to win more people over to the Java platform. That thinking leads them to wanting to support Ruby and Ruby on Rails on the Java platform. This is not the end of the world or necessarily bad thinking. Why? Well you would think the more developers on the Java platform the "mo’ better" right? I admit that being a Groovy/Grails proponent, the attention leaves me a bit jealous, but as I said earlier, they have been doing good work and, you know, envy gets you nowhere. Still it begs the question, what about the people who are already on the Java platform doing their work? What is being done to improve their experience and to keep them happy working with the Java platform?

We believe this is a question that periodically arises when people compare the attention Sun has been giving to JRuby vs Groovy. To add a bit more to think about, why is Sun is officially supporting Jython too? If Sun is catering for the non-Java developers, convincing them to jump into the Java platform, what happens to all those developers that are happy with the Java platform? What will happen with those that are tired of it and may be considering switching out?

Groovy/Grails is native to the Java ecosystem and should be (read: is ) easier to support on the Java platform. Groovy/Grails has a far flatter (read: easier ) learning curve for existing Java developers. How do I know that it is an easier learning curve? Simple, Groovy is the single reason I have not really tried to do development work in Ruby or another dynamic language. Every time I started to drift off the reservation, for one reason or another, I found that Groovy had it already. So why give up the JVM or platform libraries of which I am very familiar? Grails, the Groovy Web Framework, is still a relatively young technology, but is already showing signs of being one of the, if not the, best Java web frameworks out there. It is amazing how Grails is picking up speed right now.

One important thing to notice is that Grails uses Groovy as a glue language but it doesn’t impose the language over the framework. Sure you can still code a Grails application in 100% Java, but you will be missing on the productivity gains a more expressive language (Groovy) can give you over your regular Java. What matters is that you still have choices, people build "hybrid" Grails applications mixing Groovy/Java as they see fit, eventually getting the job done, which is exactly what you try to accomplish in the first place.

Besides the fact that Groovy/Grails support should be far easier to achieve than Ruby/RoR support, there is the converse argument about JRuby and JRuby on Rails (JRoR?) bringing people to the Java platform. JRuby on Rails could also be viewed as a conduit for allowing development to leave the Java platform as well. Why? Well all new work could feasibly be run on native Ruby platforms if run on JRuby and, in fact, would probably run better on native Ruby platforms than inside the JVM.

The risk of people switching out of the Java platform because of RoR having better than JRoR exists, but the Java platform has a very rich ecosystem of libraries and server technologies, far richer that what Ruby offers today, which means that there is a better chance of people staying inside the Java platform that going out of it.

So, in conclusion, the question is, is it more important to convert others to the Java platform or is it more important to keep and take care of the large Java developer base on the Java platform? My answer is yes . What do I mean? Well you can’t just grow a community, you must also take care of what is already there, both aspects are important to a thriving community.

So please Sun, get past the NIH (Not Invented Here) syndrome and go hire a Groovy guy next to Mr. Nutter (no complaints for Mr. Nutter, he has been doing good stuff on the JVM for all dynamic languages). While you are at it, I am going to suggest (even though I am an Eclipse guy) putting better support in Netbeans for Groovy. I am getting a little tired of hearing how IntelliJ is by far the best environment for writing Groovy. I would also suggest improving the Eclipse plugin, but I don’t think y’all will go for that(would you?). Any help to Groovy would be in your interests, you wont regret it.

Charles Nutter and his team of developer and contributors have made great progress since Sun decided to hire him, they really have pushed JRuby to be a better implementation of the Ruby language in the JVM, we sure wish them the best, after all we all are good citizens on the JVM. Let’s also remember that Sun now has 2 full time employees working on Groovy support in NetBeans.

Tags: ,

Grails to the Rescue (Dave Klein)

, June 18th, 2008

Original Source

Dave Klein writes an update of his current project with Grails in the real world. As it happens with many J2EE projects this one had derailed from a healthy schedule and is nearing a final unmovable dead-line (sounds familiar?). To add insult to injury it relies on JSF/EJB, so you can bet there are thousands of configuration files and minor setbacks communicating the whole set of components. Being quite the jovial and enthusiast guy Dave is [Editor’s note: I have the pleasure of meeting Dave in previous occasions] he quickly started to turn around the project inch by inch with the aid of Grails and his team.

Dave writes

Everyone in software development knows what a death march is but not as many are familiar with a forlorn hope. The term comes from the time when wars were fought over fortresses or walled cities. Cannons were used to make a breach in the walls big enough to send troops into. Needless to say, the first troops to go into those breaches did not fare well. So, the first unit to be sent in became known as a forlorn hope. It was often a volunteer unit with the promise of fame, glory and military advancement for those that survived.

I’ve read and heard about death march software projects before but I had never experienced one until recently. About a month ago I was put in charge of a 2 1/2 year JSF/EJB project that had 8 months left and was less than half done. (By the way, that’s my excuse for not blogging in a while. It’s not as good as Glen Smith’s excuse but it’s all I’ve got) At first this was quite disheartening. I assessed the situation and made it clear that there was no way that we could meet the deadline but was told to just “do the best we could”. So, I marched on…

Then, as I dug into the project more, I discovered that there were major pieces of the application that were isolated enough that they could be done in a different environment without impacting the overall system. Grails to the rescue. We are now using Grails for most of the remaining development and gaining momentum quickly. Two of the four of us on this team have Grails experience but the other two are coming up to speed very quickly and, I might add, enjoying their jobs more than they have for some time. One of the pleasant side effects of using Groovy and Grails is increased job satisfaction and motivation.

Though it looks that the team will not be able to make the deadline (miracles can only happen so often) it still good to know that they are making great progress turning a barely alive project into a forlon hope. We also hope Dave is able to share some war stories from this endeavor.

Tags: ,

Mastering Grails: Grails and the Mobile Web (Scott Davis)

, June 17th, 2008

Original Source

Scott Davis continues his Mastering Grails series with a new chapter: Grails and the Mobile Web. He writes at the introductory section:

These days, thankfully, it’s rare to see a Web site include the disclaimer "Best viewed using [Browser X]." Modern Ajax libraries such as Prototype, Dojo, and YUI do a reasonable job of abstracting away the remaining differences among Firefox, Internet Explorer, and Safari. But people visiting your Web site from a Nokia, Motorola, or Apple cell phone might not enjoy the same degree of browser independence. Even the latest mobile browsers that claim "full HTML support" can benefit from a few simple tweaks to the Web content. This article shows you how to optimize your Grails applications for mobile browsers.

If you’re wondering why you should even bother with making your Web site mobile-friendly, the numbers in the Mobile Web use on the rise sidebar might convince you. As impressive as the global statistics are, my interest in a mobile-friendly Web is more personal. I bought an iPhone when they first came out in summer 2007. Since then, I have been actively seeking out Web sites that are usable on the device. Sure, I can visit any Web site (as long as it doesn’t rely on Flash or Java™ applets, which the iPhone doesn’t support). The problem is that content optimized for 800×600 resolution (or higher) doesn’t look quite as nice on a 3.5-inch screen.

The Web sites I use regularly from my phone are the ones that meet me halfway with a UI that caters to the device’s unique constraints. Substituting an m for the traditional www in popular Web sites’ URLs is a good place to start. The pages at http://m.cnn.com, http://m.yahoo.com, and http://m.google.com all look good on my phone. Some Web sites, such as http://www.twitter.com, morph to the appropriate output magically: when I’m on a computer, I get all of the features; when I visit from my phone, the content is trimmed down and fits my screen like a glove. Same URL, optimized UI. I’ll show how your site can do these things too.

He then proceeds to explain some of the formats mobile devices will accept to display web content and how to produce content in said formats from your Grails enabled application. He even targets eye-candy gadgets as the iPhone. He finalizes the article by giving some advice to properly handle mobile clients without compromising your regular browser clients, mainly by

  • Creating a separate, dedicated Web site for mobile content
  • Sniffing the user agent
  • Sending back what the browser accepts

Probably some smart template management will also help to avoid file duplication, but that depends on your application needs.

As he points out at the beginning, mobile devices are everywhere, the number of connected devices increases as days go by. Given this accelerated rate and that there are more mobile/emebedded devices than computers out there, this article is a wake up call for those that want to stay in touch with customers in all ways possible, and what better way to do it by being productive with Grails at the same time.

Tags: ,