Здравствуйте. Мне нужно написать generic dao используя именно CDI (не spring, не ejb). Но я не смог нагуглить адекватный ответ по этой теме. Вот, что у меня есть:
GenericDAO interface
public interface GenericDAO <T extends Serializable> {
/**
* Adds the given entity object to DB.
*
* @param newObject the object to add in DB.
* @throws SQLException an exception that provides information
* on a database access error or other errors.
*/
void add(T newObject) throws SQLException;
/**
* Deletes the given object from DB.
*
* @param object object to delete.
* @throws SQLException an exception that provides information
* on a database access error or other errors.
*/
void delete(T object) throws SQLException;
/**
* Selects all rows from DB table and returns objective representation
* of these rows in list.
*
* @return list of all objects from DB table.
* @throws SQLException an exception that provides information
* on a database access error or other errors.
*/
List<T> findAll() throws SQLException;
/**
* Selects a row with given id from DB table and returns its
* objective representation.
*
* @param id the id of a row too look for.
* @return entity object of selected row in DB table.
* @throws SQLException an exception that provides information
* on a database access error or other errors.
*/
T findById(long id) throws SQLException;
/**
* Updates given object in DB.
*
* @param object the object to update.
*
* @throws SQLException an exception that provides information
* on a database access error or other errors.
*/
void update(T object) throws SQLException;
}
GenericDAOImpl abstract class
public abstract class GenericDAOImpl<T extends Serializable>
implements GenericDAO<T> {
protected Class<T> entityClass;
@PersistenceContext
protected EntityManager entityManager;
public GenericDAOImpl(){
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0];
}
public void add(T newObject) throws SQLException {
entityManager.persist(newObject);
}
public void delete(T object) throws SQLException {
entityManager.remove(object);
}
public List<T> findAll() throws SQLException {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entityClass);
Root<T> rootEntry = cq.from(entityClass);
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = entityManager.createQuery(all);
return allQuery.getResultList();
}
public T findById(long id) throws SQLException {
return entityManager.find(entityClass, id);
}
public void update(T object) throws SQLException {
entityManager.merge(object);
}
}
Ну и затем просто GenericDAOImpl наследуется классом с явно указанным типом (напр. ClientEntity). Так вот я не совсем понимаю, как тут использовать CDI, зачем нужен PersistenceContex и т.д. Да, сам проект сделан на Maven, деплой должен быть на Tomcat. Выразился скорее всего не точно, так что уточняйте. Спасибо.