views:

32

answers:

2

So in a recent project (a small internal tool), I want to experiment with not using an ORM tool which we typically use in all our projects. The reason is that I particularly aren't a fan of them specially in complex projects with complex object hierarchies and relationships. Using an ORM it becomes difficult to debug performance issues and other issues arising from a lot of things that the ORM library might do under the covers to "optimize".

So I was thinking of a way to lazy load certain properties of objects when I don't have the help of an ORM tool. Suppose an example:

class Student {
private List<Course> courses;

public List<Course> getCourses() {...}
public void setCourses(List<Course> courses) {...}
}

So in this case we put "courses" lazily. So I want a way to differentiate between a scenario in which the "courses" has not been loaded from the database and when "courses" is actually null even after fetching from the DB.

What are the typical ways in which I can achieve it. I was thinking that probably associate a special empty object of type "Course" denoting that actually no data exists in the DB. And the java null would mean that the data is not fetched from the DB. But this would break abstraction a bit in the sense that the getter for such lazy properties need to make the decision to accessing the DAO to getting the data.

+1  A: 

If you don't like standard ORM libraries like Hibernate, why don't you use a tool like iBATIS? iBATIS is a half-way house between Hibernate and plain SQL. Essentially it maps result sets to Java objects, however it doesn't write any SQL for you.

We switched to it from Hibernate after - like you - finding that Hibernate doesn't work so well for more complex schemas.

It does support dynamic class enhancement, however it also supports avoiding N+1 selects by putting the join in SQL (sorry, that's badly explained, but check the user guide for more info).

Anyway, to answer your actual question, I would probably implement this by using cglib or something similar to enhance a class (create a dynamic subclass). You keep a Map of properties which have been loaded or not, and then you have no need for special values.

However I think it's probably a better idea to use a library which already exists, re-inventing the wheel is never a good idea if at all possible.

Phill Sacre
A: 

You could differentiate between courses not being loaded and courses being loaded but empty by using null to imply "not loaded" and an empty Collection to imply "loaded but no courses available".

However, my preference would be to throw a RuntimeException (e.g. IllegalStateException) if the accessor is called but the data has not yet been lazily loaded. This makes debugging far easier and avoids the need for null checks littered throughout your code.

Adamski