- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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;
//..............
}
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.softech.ls360.lcms.contentbuilder.dao.impl.CourseDAOImp com.softech.ls360.lcms.contentbuilder.web.controller.CourseController.courseDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.softech.ls360.lcms.contentbuilder.dao.impl.CourseDAOImp] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:963) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1600) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.softech.ls360.lcms.contentbuilder.dao.impl.CourseDAOImp com.softech.ls360.lcms.contentbuilder.web.controller.CourseController.courseDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.softech.ls360.lcms.contentbuilder.dao.impl.CourseDAOImp] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282) ... 26 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.softech.ls360.lcms.contentbuilder.dao.impl.CourseDAOImp] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474) ... 28 more
最佳答案
您应该在 xml 中定义 bean
或者给entry of <context:component-scan base-package=" " />
关于java - 通用 DAO 实现, Controller 级别注入(inject)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22480424/
我在使用以下代码时遇到问题: function http_file_exists($url){ $f=fopen($url,"r"); if($f){ fclose($f); retu
我已经通过 Git 部署到 Azure 几个月了,没有出现重大问题,但现在我似乎遇到了一个无法克服的错误。 我创建了一个新的 Azure 网站,为正在开发的项目创建单独的预览链接。我在新站点上设置了
我已经通过flutter创建了一个App并完成了它,我想在flutter文档中阅读时进行部署。 我收到此错误: FAILURE: Build failed with an exception. * W
我在Windows 10中使用一些简单的Powershell代码遇到了这个奇怪的问题,我认为这可能是我做错了,但我不是Powershell的天才。 我有这个: $ix = [System.Net.Dn
我正在尝试使用 RapidJSON 解析从服务器接收到的数据。以下是收到的确切字符串: [ { "Node": "9478149a08f9", "Address": "172.17
我尝试为 ios 编译 OpenCV。我总是收到这些错误。我用不同版本的opencv试了一下,结果都是一样的。 我运行这个:python 平台/ios/build_framework.py ios_o
我在一台机器上做基本的发布/订阅,我的客户端是 StackExchange-Redis 的 C# 客户端,我在同一台机器上运行基于 Windows 的 Redis 服务器(服务器版本 2.8.4) 当
我有这段代码,但无法执行,请帮我解决这个问题 连接 connect_error) { die ("connection failed: " . $terhubung->connect_erro
我在 tomcat 上运行并由 maven 编译的 Web 应用程序给出了以下警告和错误。我可以在本地存储库中看到所有 JAR,但有人可以帮忙吗。 WARNING: Failed to scan JA
我正在 Windows 8 上使用 Android Studio 开发一个 android 应用程序,我正在使用一些 native 代码。突然间我无法编译我的 C 文件。当我运行 ndk-build
下面的代码对类和结构的成员进行序列化和反序列化。序列化工作正常,但我在尝试使用 oarch >> BOOST_SERIALIZATION_NVP(outObj); 反序列化时遇到了以下错误; 代码中是
如果我运行此命令“rspec ./spec/requests/api/v1/password_reset_request_spec.rb”,此文件中的所有测试都会通过。 但是,当我运行“rspec”时
我在尝试执行测试以使用 Protractor 上传文件时出错,我的代码是这个 it('it should be possible to upload a file', function() {
System.loadLibrary("nativefaceswap"); 当我运行我的应用程序时,我在 Android Studio 中发现了此类错误。在logcat中显示: java.lang.U
我希望有人能帮助我!使用任何方法或命令行的任何 SSL/HTTPS 调用均无效。 我在 Windows 10 中使用 Ubuntu Server 18.04 作为子系统。我的问题是昨天才开始出现的,因
通过删除这两个值将日期字段从 null=True 和 Blank=True 更改为 required 时,使用 db.alter 命令时遇到问题。 当以下行被注释掉时,迁移运行不会出现问题。
我第一次使用 Heroku 尝试创建应用程序(使用 SendGrid 的 Inbound Parse Webhook"和 Twilio SMS 通过电子邮件发送和接收 SMS 消息)。通过 Virtu
我正在将我的 swift 项目更新到 Xcode 7 上的 Swift 2.0。xcode 在构建项目时报告了以下错误: 命令/Applications/Xcode.app/Contents/Deve
在我的代码中,SSL 库函数 SSL_library_init() 没有按预期返回 1。我如何才能看到它返回了什么错误? 我在 SSL_library_init() 之后调用了 SSL_load_er
我正在尝试运行在以下链接中找到的答案: Asynchronously Load the Contents of a Div 但是当我这样做时,我会遇到我不太理解的错误。 我的代码: $(documen
我是一名优秀的程序员,十分优秀!