Seam + Groovy + Maven : Nice Simple Hibernate POJOs

Being a long weekend, I had a couple hours yesterday to mess around with my Maven build in the hopes of integrating Groovy and ridding myself of a lot of Hibernate boilerplate (you know, all the annoying getters/setters).

I’m currently working on a Seam-based prototype and Groovy is certainly applicable to aspects other than Hibernate but it was a good initial goal.

Required POM Changes

<build>
<plugins>
    <plugin>
        <groupId>org.codehaus.groovy.maven</groupId>
        <artifactId>gmaven-plugin</artifactId>
        <version>1.0-rc-2</version>
        <executions>
            <execution>
                <goals>
                    <goal>generateStubs</goal>
                    <goal>compile</goal>
                    <goal>generateTestStubs</goal>
                    <goal>testCompile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>

The gmaven plugin is able to cross-compile Java and Groovy. The compilation phase will generate Java stubs corresponding to the groovy classes prior to compiling the actual Java classes. This allows for seamless dependencies to exist between Groovy and Java.

It’s important to note that your Groovy sources must (by default) be in a src/main/groovy folder.

<dependencies>
    <dependency>
        <groupId>org.codehaus.groovy.maven.runtime</groupId>
        <artifactId>gmaven-runtime-default</artifactId>
        <version>1.0-rc-2</version>
    </dependency>
</dependencies>

Results

Simple as that. Unit tests passed!

I’m able to take a class that looked like:

@Entity
public class Annotation
{
    private Long id;
    private String name;

private Specimen specimen; private Patient patient;

/** * Getter for property 'id'. * * @return Value for property 'id'. */ @Id @GeneratedValue public Long getId() { return id; }

/** * Setter for property 'id'. * * @param id Value to set for property 'id'. */ public void setId(Long id) { this.id = id; } ... }

and make it look like:

@Entity
public class Annotation
{
    @Id @GeneratedValue
    Long id;

@Length(max=50) @NotNull String name;

@ManyToOne @JoinColumn(name = "specimen_id") Specimen specimen;

@ManyToOne @JoinColumn(name = "patient_id") Patient patient; }

Much simpler and without a lot of unnecessary boilerplate.

Gotchas

Just a couple of things to be aware of. Simple stuff really if you actually read documentation and know what you’re doing :)

Firstly, Groovy sources have to live in src/main/groovy.

Secondly, don’t add private modifiers to your attributes if you want the generated Groovy stubs to include getters/setters. This is probably more obvious if you’re creating your Groovy classes from scratch. I forgot to remove them when I was converting from a Java POJO and had a minor WTF moment.

Next step will be to see how much Groovy could potentially be leveraged for other aspects of the system.