当前位置: 首页 > 知识库问答 >
问题:

通用DAO实现,注入失败@控制器级

魏翰
2023-03-14
  import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.Transient;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;


/**
 * Generic DAO implementation class that provides basic Data access and
 * manipulation functionality
 * 
 * @author syed.ammar
 * 
 */
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {

    private static Logger logger = Logger.getLogger(GenericDAOImpl.class);

    @SuppressWarnings("unchecked")
    protected Class<T> clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    @PersistenceContext
    protected EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public T save(T entity) throws DataAccessException {
        logger.debug("Merging Object of Type: " + entity.getClass().getCanonicalName());
        entity = entityManager.merge(entity);
        return entity;
    }

    @Override
    public void persist(T entity) throws DataAccessException {
        logger.debug("Persisting Object of Type: " + entity.getClass().getCanonicalName());
        entityManager.persist(entity);
    }


    /**
     * This method update record in database
     * 
     * @param updatableObj
     *            - the updated copy to merge
     * @return the updated, registered persistent instance
     * */
    @Override
    public T update(T entity) {
        return save(entity);
    }

    /**
     * Delete the given entity.
     * 
     * @param entityClass
     *            - the entityClass to delete
     * */
    @Override
    public void delete(T entity) {
        logger.debug("Delete entity of Type: " + entity.getClass().getCanonicalName());
        entityManager.remove(entity);
    }

    /**
     * Delete all given entities.
     * 
     * @param entities
     *            - the entities to delete
     * */
    public void deleteAll(List<T> entities) {
        for (T entity : entities) {
            delete(entity);
        }
    }

    /**
     * Delete Entity by Id
     * @param id
     *      - Entity Id 
     */
    @Override
    public int deleteById(Long id) {
        Query deleteQuery = entityManager.createQuery("DELETE FROM " + clazz.getName() + " entity WHERE entity.id=:id");
        deleteQuery.setParameter("id", id);
        return deleteQuery.executeUpdate();     
    }

    /**
     * Delete Entity by Customer
     * @param customer
     *      - Customer Entity 
     */
/*  @Override
    public int deleteByCustomer(Customer customer) {
        Query deleteQuery = entityManager.createQuery("DELETE FROM " + clazz.getName() + " entity WHERE entity.customer=:customer");
        deleteQuery.setParameter("customer", customer);
        return deleteQuery.executeUpdate();
    }
*/  
    /**
     * Delete Entity by Reseller
     * @param reseller
     *      - Reseller Entity 
     */
/*  @Override
    public int deleteByReseller(Reseller reseller) {
        Query deleteQuery = entityManager.createQuery("DELETE FROM " + clazz.getName() + " entity WHERE entity.customer.reseller=:reseller");
        deleteQuery.setParameter("reseller", reseller);
        return deleteQuery.executeUpdate();
    }
*/
    /**
     * Read the entity instance of the given class with the given id, throwing
     * an exception if not found. Retrieves read-write objects from the
     * hibernate UnitOfWork in case of a non-read-only transaction, and
     * read-only objects else.
     * @param id
     *            - Identity key of the desired object
     * @return the entity instance
     * */
    @Override
    public T getById(Long id) {
        logger.debug("getById:" + id + ", T class: " + clazz );
        return entityManager.find(clazz, id);
    }

    @Override
    public List<T> getResultList(String jpql, Map<String, Object> queryParams) {
        logger.debug("Query: " + jpql);
        Query query = entityManager.createQuery(jpql.toString());
        for(Map.Entry<String, Object> entry : queryParams.entrySet()){
            query.setParameter(entry.getKey(), entry.getValue());
        }
        @SuppressWarnings("unchecked")
        List<T> resultList = (List<T>) query.getResultList();
        return resultList;
    }

    /**
     * Generic search method without sort column and direction which searches
     * the record depending upon property values set in the passed model bean. 
     * This method has been deprecated and will be removed soon. Create Query 
     * specific methods in related Entity DAO's instead.
     * 
     * @param entity
     *            Entity with data set for criteria search
     * @return List of searched model beans by applying the passed values of
     *         model bean as criteria
     */
    @Override
    @Deprecated
    public List<T> search(T entity) {
        return search(entity, null, null);
    }

    /**
     * Generic search method which searches the record depending upon property
     * values set in the passed model bean. 
     * This method has been deprecated and will be removed soon. Create Query 
     * specific methods in related Entity DAO's instead.
     * 
     * @param entity
     *            Entity with data set for criteria search
     * @param sortByColumn
     *            Name of column to be used for sorting result
     * @param sortDirection
     *            1: ASC 2:DESC
     * @return List of searched model beans by applying the passed values of
     *         model bean as criteria
     */
    @Override
    @Deprecated
    @SuppressWarnings("unchecked")
    public List<T> search(T entity, String sortByColumn, Long sortDirection) {
        List<Object> params = new ArrayList<Object>();
        String query = "SELECT entity FROM " + clazz.getName() + " entity";

        Field[] publicFields = entity.getClass().getDeclaredFields();
        for (Field field : publicFields) {
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(entity);
            } catch (IllegalArgumentException e) {
                logger.error("", e);
            } catch (IllegalAccessException e) {
                logger.error("", e);
            }
            if (value == null
                    || Collection.class.isAssignableFrom(field.getType())
                    || java.lang.reflect.Modifier.isStatic(field.getModifiers())
                    || field.getAnnotation(Transient.class) != null) {
                continue;
            }
            if (field.getType().equals(String.class)) {
                if (query.contains("where")) {
                    query = query + " and " + field.getName() + " like ?"
                            + params.size();
                } else {
                    query = query + " where " + field.getName() + " like ?"
                            + params.size();
                }
                params.add("%" + value.toString() + "%");
            } else if (field.getType().equals(Date.class)) {
                Date startDateTime = null;
                Date endDateTime = null;
                String startTime = DATE_FORMAT.format(value) + " 00:00:00";
                String endTime = DATE_FORMAT.format(value) + " 23:59:59";
                try {
                    startDateTime = DATE_TIME_FORMAT.parse(startTime);
                    endDateTime = DATE_TIME_FORMAT.parse(endTime);
                } catch (ParseException e) {
                    logger.error("", e);
                }
                if (startDateTime == null || endDateTime == null) {
                    continue;
                }
                if (query.contains("where")) {
                    query = query + " and " + field.getName() + " between ?"
                            + params.size() + " and ?" + (params.size() + 1);
                } else {
                    query = query + " where " + field.getName() + " between ?"
                            + params.size() + " and ?" + (params.size() + 1);
                }

                params.add(startDateTime);
                params.add(endDateTime);
            } else {
                if (query.contains("where")) {
                    query = query + " and " + field.getName() + " = "
                            + params.size();
                } else {
                    query = query + " where " + field.getName() + " = ?"
                            + params.size();
                }
                params.add(value);
            }
        }

        Query queryObj = entityManager.createQuery(query);

        // Check is sorting parameters are not not blank or null, apply sorting
        // criteria
        if (sortByColumn != null && sortDirection != null) {
            if (sortDirection == 1L) {
                query = query + " Order By " + sortByColumn + " ASC";
            } else {
                query = query + " Order By " + sortByColumn + " DESC";
            }
            if (params.size() > 0) {
                for (int i = 0; i < params.size(); i++) {
                    queryObj.setParameter(i, params.get(i));
                }
            }
        }

        return queryObj.getResultList();
    }

    @Override
    public List<T> getAll() {
        return getAll(null, null);
    }

    @Override
    public List<T> getAll(String sortByColumn, Long sortDirection) {
        String query = "SELECT entity FROM " + clazz.getName() + " entity";
        if (sortByColumn != null && sortDirection != null) {
            if (sortDirection == 1L) {
                query = query + " Order By " + sortByColumn + " ASC";
            } else {
                query = query + " Order By " + sortByColumn + " DESC";
            }
        }
        @SuppressWarnings("unchecked")
        List<T> resultList = (List<T>) entityManager.createQuery(query).getResultList();
        return resultList;
    }
    /**
     * Generic find method which identify the exact records depending upon
     * property values set in the passed model bean else null will be returned
     * 
     * @param entity
     *            Entity with data set for criteria search
     * @return List of identified model beans by applying the passed values of
     *         model bean as criteria
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<T> find(T entity) {
        List<Object> params = new ArrayList<Object>();
        String query = "SELECT entity FROM " + entity.getClass().getName()
                + " entity";

        Field[] publicFields = entity.getClass().getDeclaredFields();
        for (Field field : publicFields) {
            field.setAccessible(true);
            Object value = null;

            try {
                value = field.get(entity);
            } catch (IllegalArgumentException e) {
                logger.error("", e);
            } catch (IllegalAccessException e) {
                logger.error("", e);
            }
            if (value == null
                    || Collection.class.isAssignableFrom(field.getType())
                    || java.lang.reflect.Modifier.isStatic(field.getModifiers())
                    || field.getAnnotation(Transient.class) != null) {
                continue;
            }

            if (field.getType().equals(Date.class)) {
                Date startDateTime = null;
                Date endDateTime = null;
                String startTime = DATE_FORMAT.format(value) + " 00:00:00";
                String endTime = DATE_FORMAT.format(value) + " 23:59:59";               
                try {
                    startDateTime = DATE_TIME_FORMAT.parse(startTime);
                    endDateTime = DATE_TIME_FORMAT.parse(endTime);
                } catch (ParseException e) {
                    logger.error("", e);
                }
                if (startDateTime == null || endDateTime == null) {
                    continue;
                }
                if (query.contains("where")) {
                    query = query + " and " + field.getName() + " between ?"
                            + params.size() + " and ?" + (params.size() + 1);
                } else {
                    query = query + " where " + field.getName() + " between ?"
                            + params.size() + " and ?" + (params.size() + 1);
                }
                params.add(startDateTime);
                params.add(endDateTime);
            } else {
                if (query.contains("where")) {
                    query = query + " and " + field.getName() + " = ?"
                            + params.size();
                } else {
                    query = query + " where " + field.getName() + " = ?"
                            + params.size();
                }
                params.add(value);
            }
        }
        if (params.size() > 0) {
            Query queryObj = entityManager.createQuery(query);

            for (int i = 0; i < params.size(); i++) {
                queryObj.setParameter(i, params.get(i));
            }
            return queryObj.getResultList();
        } else {
            return null;
        }
    }
}

///自动接线

@Controller
public class CourseController   {

//  @Autowired
//  private SearchService searchService;

    @Autowired
    CourseDAOImp courseDAO;
    //..............
}

共有1个答案

娄鹤轩
2023-03-14

您应该用xml定义bean

或者给出 条目

 类似资料:
  • 我在Ubuntu虚拟机上使用kubeadm(V1.18)建立了一个k8s集群。现在我需要添加一个入口控制器。我决定使用nginx(但我对其他解决方案持开放态度)。我根据文档中的“裸机”部分安装了它: 安装在我看来很好: 我怀疑是DNS,但其他NodePort服务正按预期工作,而DNS在集群内工作。 我唯一能看到的是,我没有default-http-backend,这里的文档中提到了这个defaul

  • 我正在尝试设置我的第一个Kubernetes集群,它似乎已经设置好,直到nginx-ingress控制器。以下是我的集群信息:节点:三个RHEL7和一个RHEL8节点,主服务器运行在RHEL7Kubernetes服务器版本:1.19.1网络使用:Frannel coredns运行良好。在所有节点上禁用selinux和防火墙 然后,我按照以下页面中的说明安装了nginx入口控制器:https://d

  • 我的项目有问题 线程“main”组织中出现异常。jboss。焊接例外情况。DeploymentException:WELD-001408:JpaDAO类型与限定符@Default在注入点[BackedAnnotatedField]@InjectPrivate teste的未满足依赖关系。看法最重要的刀 JpaDAO(仅用于测试,未完全实现): 我的: 还有我的: 我做错了什么?

  • ...Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers. 控制器作为应用程序逻辑的处理入口,它会负责去调用你已经实现的一些服务。通常,一个控制器会接收并解析用户的请求,然后把它转换成一个模型交给视图,由视图渲染出页面最终呈现

  • 有一个项目大约有20个控制器。每个控制器都有其相应的测试类。当我们尝试添加新的controller tests类时,以前运行良好的一些测试开始随机失败。如果使用@Ignore注释任何控制器测试类,测试将恢复正常。 这是失败测试抛出的异常: org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常为java.lang.Illega