我的应用程序使用的是 DAO 模式。我是否应该将实现方法设为“静态”?
我说的是这个具体的实现:
- findByIdentifier(字符串标识符)
但也关于通用实现:
- E getByID(K ID);
- 列出 findAll();
- 保存(E实体);
- 更新(E实体);
- 删除(E实体);
感谢您的建议!
public interface DaoBase<K, E> {
E getByID(K ID);
List<E> findAll();
void save(E entity);
void update(E entity);
void delete(E entity);
}
public interface DaoLanguage extends DaoBase<Long, LanguageEntity> {
LanguageEntity findByIdentifier(String identifier);
}
我正在使用 JPA 来持久化所有实体类。
public class JpaDaoLanguage extends JpaDaoBase<Long, LanguageEntity> implements DaoLanguage {
public LanguageEntity findByIdentifier(String identifier) {
LanguageEntity language = (LanguageEntity) entityManager.createQuery(
"select lan from LanguageEntity as lan where lan.identifier = ?1")
.setParameter(1, identifier)
.getSingleResult();
return language;
}
}
通用基础实现
public abstract class JpaDaoBase<K, E> implements DaoBase<K, E> {
protected EntityManager entityManager;
protected Class<E> entityClass;
@SuppressWarnings("unchecked")
public JpaDaoBase() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass()
.getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass
.getActualTypeArguments()[1];
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("CyberLabPersistenceUnit");
entityManager = factory.createEntityManager();
}
@Override
public E getByID(K ID) {
return entityManager.find(entityClass, ID);
}
@SuppressWarnings("unchecked")
@Override
public List<E> findAll() {
Query q = entityManager.createQuery("SELECT e FROM "
+ entityClass.getName() + " e ");
return (List<E>) q.getResultList();
}
@Override
public void save(E entity) {
entityManager.persist(entity);
}
@Override
public void update(E entity) {
entityManager.merge(entity);
}
@Override
public void delete(E entity) {
entityManager.remove(entity);
}
}