开发者

Getting DAOs for Table-per-Hierarchy structure

Let's assume I have a User class and two subclasses Employee and Customer. I implemented this hierarchy as a table-per-hierarchy in DB with a column for specifying the type of user. I need to return the right type of object when querying this table.

Do I need separate DAOs for each type of object like CustomerDAO or EmployeeDAO, so each return their respective Customer and Employee objects. If so how to get them from DAOFactory without using:

if(type.equlas('customer'))
    return custom开发者_StackOverflow社区erDao;
else
    retrun employeeDao;

Because the types implementing User could change and I don't want to change conditions every time.

Or is there any other way? Any idea would be appreciated.

Note: I'm not using any ORM framework and not planning to use one.


If your persistence code for each type is the same, then you could have 1 generic DAO.

So your user dao, could be something like:

interface DAO<T, ID> {
  T create(T t);
  T read(ID id);
  T update(T t);
  void delete(T t);  
}

class UserDAO<T extends User> implements DAO<T> {
    // Your methods for crud operations will be limited to types of User.
}

Then your factory class could instantiate the correct DAO simply by specifying the correct type.

class DAOFactory {
  public UserDAO<Employee> getEmployeeDAO() {
    return new UserDAO<Employee> ();
  }
}

Regards
Yusuf

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜