Skip to main content

Quick and Easy Object Persistence: pBeans + Groovy Beans

Posted by mdi on May 18, 2004 at 9:09 AM PDT

Laziness: The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it.


-- Larry Wall, Tom Christiansen, and Randal L. Schwartz, Programming Perl, 2nd Edition

I started my programming life in Perl, and I am a lazy programmer. I get frustrated when I have to write duplicate code, or put information in more than one place. I'll search the web for days, try sample applications in 10 different frameworks, and write hundreds of lines of test code to find a solution that saves me half an hour. Now that's lazy.

I've been looking at persistence layers and frameworks lately. I don't like having SQL in my objects, partially because it makes things more brittle, and partially because I don't like writing SQL anywhere. I just want to write classes and instantiate objects, manipulate them for a while, and then have them stick around. I don't really care about the database itself. (In fact, most of the time I don't need a database, that's just a simple way to store stuff.)

I'm sure that somewhere there is a good list and comparison of available persistence layers, so I won't try to duplicate that here. What I will say is that almost everything I looked at required at least one of the following, and usually more than one:

  • Extending a framework class
  • Implementing a complex interface
  • Writing XML mapping files
  • Writing mapping classes
  • Generating a database schema at compile time
  • Code generation

One word: gross.

Prevayler-style in-memory storage is kind of cool, but it also places restrictions on how you structure your client classes. I don't want restrictions, I don't want extra work, and I don't want duplicated code or information. How do I do it?

pBeans is one way. It really is as simple as I was looking for. Make some Beans, tag them with implements Persistent, make a store, and then put objects in the store and take them out. No SQL (one exception; read on), no XML, no mapping files. Free as in speech. Currently works with MySQL, Postgres, and SQL Server, and should be fairly easy to get working on other databases.

Here's how it works:

  1. Create an instance of net.sourceforge.pbeans.data.GenericDataSource
  2. Configure that DataSource with a JDBC driver and a database URL
  3. Use that DataSource to get an instance of net.sourceforge.pbeans.Store
  4. Create some JavaBeans
  5. Call insert(), save(), delete(), and select() on the Store with those beans
  6. Laugh at how easy it was to get your objects stored in the database

Notice that we never created any database tables? pBeans did that for us. So far, I'm happy.

Well, mostly happy. JavaBeans make persistence easy, but violate another of my lazy principles: duplication. I can't stand writing getters and setters for every field. Java is already too verbose for my tastes, coming from a loose typing background. 2 copy-paste methods for every field is too much. Enter Groovy Beans.

Groovy is quite possibly the best thing I've encountered in the Java world, period. It makes writing for the Java platform enjoyable for me, and it really helps my wrists not hurt so much. Here's an example:


Java bean:
public class User {

    private Integer id;
    private String name;
    private String favoriteColor;

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getFavoriteColor() {
        return favoriteColor;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setFavoriteColor(String favoriteColor) {
        this.favoriteColor = favoriteColor;
    }

}

Groovy bean:
class User {
   Integer id
   String name
   String favoriteColor
}

Groovy takes care of the rest behind the scenes.


So, here's a basic object persistence example in 20 lines of Groovy:
import net.sourceforge.pbeans.data.*
import net.sourceforge.pbeans.*

dataSource = new GenericDataSource()
dataSource.setDriverClassName("com.mysql.jdbc.Driver")
dataSource.setUrl("jdbc:mysql://localhost/test?user=test&password=test")

store = new Store(dataSource)

class User implements Persistent {
    Integer id
    String name
    Integer age
    String hometown
}

joe = new User(name:"Joe User", age:43, hometown:"Bay Minette, AL")
store.insert(joe)
newjoe = store.selectSingle(User.class, "name", "Joe User")
assert newjoe.hometown == "Bay Minette, AL"

It's coding even the laziest programmer can handle.


Exception to the no SQL statement: I wanted id to be unique, and didn't have the time to figure out how to make pBeans do that for me. After the first invocation, when pBeans had created the table for me, I manually altered the id column to be primary key and auto increment. You'll have to do that once for each class. There's probably a way to make pBeans do that. Let me know if you figure it out.

Related Topics >>