pátek, září 21, 2007

Apache Cayenne - easier user API

I really like ActiveRecord and I'm also watching the ActiveObjects ORM(JAVA). This project is very nice but still not mature enough for the real life project. But being inspired from the ActiveObjects I created a wrapper for Apache Cayenne that uses EntityManager approach. Instead a common DAO like scenario of using services for each model, I can now use one EntityManager that serves for all models.

The solution requires Java 5 as generics and some other features are being used.
Here are just a few code snippets of how it can be used.


Various syntax examples:

EntityManager em;
// create and save object
Contact contact=em.create(Contact.class);
em.saveChanges();

// find object by id
Contact contact=em.findById(Contact.class, id);

// find object by property
Contact contact=em.findFirstByProperty (Contact.class, "username", form.getFieldValue("username"));

// find many objects by property
List contacts=em.findAllByProperty(Contact.class, "subdomain.name", form.getFieldValue("subdomain"));

// find objects based on user defined query
List contacts=em.findAllByQuery(
Contact.class,
Query.where("subdomain = $subdomain and age > $age")
.param("subdomain", current_user.getSubdomain())
.param("age",18)
.order("lastname",true)
.offset(200)
.limit(10)
.include(Contact.ROLE_ARRAY_PROPERTY)
);
Its just a special API interface that let you work with Apache Cayenne in very easy way.
I can share the code if someone find it usefull.