0
我的應用程序正在使用DAO模式。 我應該讓實現方法「靜態」還是不是?DAO模式 - 使用靜態還是非靜態方法?
我談論這個具體實現:
- findByIdentifier(字符串標識符)
而且關於通用實現:
- ËgetByID(K ID);
- List findAll(); (E entity);
- save(E entity);
- update(E entity);
- 刪除(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);
}
}