I'm using Hibernate. The question is at the bottom.
The current strategy
It's simple.
First of all, I have a basic Dao<T>
.
public class Dao<T> {
private Class<T> persistentClass;
private Session session;
public Dao(Class<T> persistentClass) {
this.persistenClass = persistentClass;
this.session = HibernateUtil.getCurrentSession();
}
It's nice as a base class and it passes the most common methods up to its Session
.
public T get(Serializable id) {
@SuppressWarnings("unchecked")
T t = (T) this.session.get(this.persistentClass, id);
return t;
}
protected Criteria getCriteria() {
return this.session.createCriteria(this.persistentClass);
}
When there's need to use queries on the model, it goes into a specific DAO for that piece of model, which inherits from Dao<T>
.
public class DaoTask extends Dao<Task> {
public DaoTask() {
super(Task.class);
}
public List<Task> searchActiveTasks() {
@SuppressWarnings("unchecked")
List<Task> list = (List<Task>) this.getCriteria()
.add(Restrictions.eq("active", true))
.list();
return list;
}
}
This approach has always worked well.
However...
However, today I found that many times an instance needs reattachment to the Session
and a line similar to the following ends up happening:
new Dao<Book>(Book.class).update(book);
... which I find to be bad, because
- I don't like specifying the redundant
Book.class
- If ever a
DaoBook
arises, this construct will become obsolete.
So I turned Dao<T>
into an abstract class, and went on to refactor the old code.
Question
In order to remove the Dao<T>
references from the codebase, I thought of two approaches:
- Create specific DAOs for every class that ever needs attachment, which would generate many almost empty
DaoBook
s and the sort. - Create a class that owns a
Dao<Object>
and exposes only the attachment methods (i.e.save()
,update()
etc).
I'm tending to go with #2, but I thought this "AttacherDao
" pattern might be bad, so I'd like your opinion.
Any cons for #2? Also, do you find anything wrong with "the current strategy"?