Is this a good approach for a custom object-relational mapping in Java?
I'm developing a sample Java application that uses Oracle's built-in "HR" database schema. I'd like to treat table rows as Java objects. One of the tables in the HR schema, EMPLOYEES, is self-referential. It has a MANAGER_ID column which contains (if not NULL) a foreign key to another row in the EMPLOYEES table.
In object-oriented terms, the problem is how to get access to a given Employee object's manager (which is another Employee object). Eager loading doesn't seem to be a good solution, since the given Employee object's manager could also have a manager, and so on. The number of objects to eagerly load in this situation is unbounded.
What I've decided to do so far is eagerly load the MANAGER_ID field when instantiating an Employee object. Then, when the Employee's manager Employee object is requested (through a getManager() method), the latter will be lazily loaded. In code:
Code:
public class Employee
{
private int id;
private int managerId;
private Employee manager;
public int getId()
{
return id;
}
public Employee getManager()
{
if(manager == null && managerId > 0)
{
// Lazy loading!
}
return manager;
}
public void setManager(Employee manager)
{
this.manager = manager;
this.managerId = manager.getId();
}
}
So is this a good approach? The only issue I have with it is how to implement the lazy loading. It would seem that an Employee object needs a reference to its instantiator -- presumably that would be the same thing that would instantiate its manager Employee object.
Also, I know I could just use one of the many ORM frameworks out there instead of rolling my own, but I'm doing this on my own to gain more insight into the underlying process(es).