我在使用Spring Boot和Jersey构建的restful Web服务应用程序中实现了泛型dao层。我有一些相同的资源控制器,以避免重复相同的方法,我想创建一个GenericControllers或GenericResources控制器。在这些控制器中注入genericDao时遇到问题。对于这些通用资源,我不需要特定的服务。
public interface IGenericDAO<T extends Serializable> {
T findOne(final Integer id);
List<T> findAll();
T create(final T entity);
void update(final T entity);
void delete(final T entity);
void deleteById(final Integer id);
}
public abstract class AbstractGenericDAO<T extends Serializable> implements IGenericDAO<T> {
private final Class<T> clazz;
@SuppressWarnings("unchecked")
public AbstractGenericDAO() {
this.clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
/**
* getSession() from EntityManager which is already configured in spring-boot-starter-data-jpa.
* We inject EntityManager instead of SessionFactory
*/
@Autowired
private EntityManager entityManager;
protected Session getCurrentSession() {
return this.entityManager.unwrap(Session.class);
}
@Override
public T findOne(Integer id) {
// TODO Auto-generated method stub
return (T) getCurrentSession().get(this.clazz, id);
}
@Override
public List<T> findAll() {
// TODO Auto-generated method stub
CriteriaQuery<T> cq = getCurrentSession().getCriteriaBuilder().createQuery(this.clazz);
cq.from(this.clazz);
return getCurrentSession().createQuery(cq).getResultList();
}
@SuppressWarnings("unchecked")
@Override
public T create(T entity) {
// TODO Auto-generated method stub
return ((T) getCurrentSession().save(entity));
}
@Override
public void update(T entity) {
// TODO Auto-generated method stub
getCurrentSession().saveOrUpdate(entity);
}
@Override
public void delete(T entity) {
// TODO Auto-generated method stub
getCurrentSession().delete(entity);
}
@Override
public void deleteById(Integer id) {
// TODO Auto-generated method stub
T entity = this.findOne(id);
this.delete(entity);
}
}
这是我的问题。我想在这里使用泛型资源:
public class GenericResource<T extends Serializable> extends AbstractGenericDAO<T> {
/*@GET
@Secured({"ROLE_ADMIN"})
public Response list() {
return Response.ok().entity(dao.findAll()).build();
}*/
}