GenericDao
私にとっては、GenericDAO が「ジェネリック」である場合、必要なインスタンスは 1 つだけで、その 1 つのインスタンスですべてを実行できます。
私はあなたが腹を立てるのは繰り返しである(そして私はあなたに同意する).
たとえば、エンティティ クラスをジェネリック メソッドに渡すことができます。
- public void save(Class, E...) : E 型の 1 つ以上のインスタンスを保存できます。E はエンティティの 1 つです。
- public E load(Class, Long id) : エンティティをロードします。
...
/** Assuming the entities have a superclass SuperEntity with getIdent(). */
public class GenericDaoImpl implements GenericDao {
/** Save a bunch of entities */
public void save(SuperEntity... entities) {
for(SuperEntity entity : entities) {
getSession().save(entity);
}
}
/** Load any entity. */
public <E extends SuperEntity> E load(Class<E> entityClass, Long ident) {
return (E)getSession().load(entityClass, ident);
}
// other generic methods
}
変異体
私たちのアプリケーションでは、実際にこのためのバリアントがあります。Dao ごとに多くの特定の要求があるため、とにかく特定の Dao クラスが必要です (クラスを作成して接続します)。そのため、定義されない Dao の特殊なケースを回避するために、特定の Dao クラスをすぐに作成します。
コーディング
ただし、コードを繰り返すことは決してありません。すべての Daos は GenericDao を拡張し、コンストラクターで必要な Class パラメーターを提供します。サンプルコード (完全ではなく、基本的な考え方を理解するのは簡単です):
public abstract class GenericDaoImpl<E extends SuperEntity>
implements GenericDao<E> {
/** Available for generic methods, so it is not a parameter
* for the generic methods. */
private final Class<E> entityClass;
protected GenericDaoImpl(Class<E> entityClass) {
this.entityClass = entityClass;
}
// generic implementation ; can be made efficient, as it may
// send the orders as a batch
public void save(E... entities) {
for(SuperEntity entity : entities) {
getSession().save(entityClass, entity.getIdent());
}
// possibly add flushing, clearing them from the Session ...
}
// other generic methods
}
public class PersonDaoImpl extends GenericDaoImpl<Person>
implements PersonDao {
/** Constructor, instanciating the superclass with the class parameter. */
public PersonDaoImpl() {
super(Person.class);
}
/** Specific method. */
public List<Person> findByAge(int minAge, int maxAge) {
//....
}
}
配線
すべての豆を配線することは致命的ではありません。現在、多くの自動配線ポリシーがあるため、心配する必要はありません。Spring でそれらを参照して
ください http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config