Hibernate 泛型DAO和包装器
为了完成uni项目,我需要创建一个通用DAO 我遵循了曼宁的书《用hibernate实现Java持久化》中的一般DAO设计。en最终采用了以下方法Hibernate 泛型DAO和包装器,hibernate,dao,Hibernate,Dao,为了完成uni项目,我需要创建一个通用DAO 我遵循了曼宁的书《用hibernate实现Java持久化》中的一般DAO设计。en最终采用了以下方法 findById(ID id, boolean lock) findAll() findByExample(T example) makePersistent(T entity) makeTransient(T entity) flush() clear() 问题是这些方法对于我的项目是不够的,我的项目包括搜索实体、对它们排序和分页。我知道我可以通
findById(ID id, boolean lock)
findAll()
findByExample(T example)
makePersistent(T entity)
makeTransient(T entity)
flush()
clear()
问题是这些方法对于我的项目是不够的,我的项目包括搜索实体、对它们排序和分页。我知道我可以通过创建一个类似
List<T> find(DetachedCriteria dc)
这就意味着要打电话给:
DetachedCriteria dc = new DetachedCriteria();
dc.add(Restrictions.like(property, value)
谢谢在通用DAO接口中提供了您所需的一切。如果你可以用它来替换你自己的东西,或者如果你只是想找参考的话,你可以浏览它的代码。它支持分页等功能。使用此功能。它具有分页和lucene集成。我为我的一个项目创建了这个。确保每一把刀都从它开始延伸。拿出你不需要的东西
package com.isavera.hibernate;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.criterion.Criterion;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.isavera.actions.utils.Application;
@SuppressWarnings("serial")
@Transactional
public abstract class AbstractDAOImpl<E> extends HibernateDaoSupport implements AbstractDAO<E>, ApplicationContextAware {
private static final String CLASS_NAME = AbstractDAOImpl.class.getName();
private static final Logger LOG = Logger.getLogger(CLASS_NAME);
private static ApplicationContext _applicationContext;
private final Class<? extends E> _entityClass;
/**
* @param entityClass
*/
public AbstractDAOImpl(Class<? extends E> entityClass) {
super();
_entityClass = entityClass;
}
public void delete(E entity) {
LOG.entering(CLASS_NAME, "delete", entity);
getHibernateTemplate().delete(entity);
LOG.exiting(CLASS_NAME, "delete");
}
public void evict(E entity) {
LOG.entering(CLASS_NAME, "evict", entity);
getHibernateTemplate().evict(entity);
LOG.exiting(CLASS_NAME, "evict");
}
public void deleteAll(Collection<E> entities) {
getHibernateTemplate().deleteAll(entities);
}
@SuppressWarnings("unchecked")
public List<E> findByNamedQuery(String queryName) {
return getHibernateTemplate().findByNamedQuery(queryName);
}
@SuppressWarnings("unchecked")
public List<E> findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) {
return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramName, value);
}
@SuppressWarnings("unchecked")
public List<E> findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) {
return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values);
}
public E get(Serializable id) {
LOG.entering(CLASS_NAME, "get", id);
@SuppressWarnings("unchecked")
E entity = (E) getHibernateTemplate().get(_entityClass, id);
LOG.exiting(CLASS_NAME, "get", entity);
return entity;
}
public List<E> get(Criterion... criterion) {
LOG.entering(CLASS_NAME, "get", criterion);
Criteria criteria = getSession().createCriteria(_entityClass);
for (Criterion c : criterion) {
criteria.add(c);
}
@SuppressWarnings("unchecked")
List<E> list = new ArrayList<E>(criteria.list());
LOG.exiting(CLASS_NAME, "get", list);
return list;
}
public boolean isEntityAttached(E entity) {
return getHibernateTemplate().getSessionFactory().getCurrentSession().contains(entity);
}
public E load(Serializable id) {
LOG.entering(CLASS_NAME, "load", id);
@SuppressWarnings("unchecked")
E entity = (E) getHibernateTemplate().load(_entityClass, id);
LOG.exiting(CLASS_NAME, "load", entity);
return entity;
}
public E load(Serializable id, LockMode lockMode) {
LOG.entering(CLASS_NAME, "load", new Object[] { id, lockMode });
@SuppressWarnings("unchecked")
E entity = (E) getHibernateTemplate().load(_entityClass, id, lockMode);
LOG.exiting(CLASS_NAME, "load", entity);
return entity;
}
public void load(E entity, Serializable id) {
LOG.entering(CLASS_NAME, "load", new Object[] { entity, id });
getHibernateTemplate().load(entity, id);
LOG.exiting(CLASS_NAME, "load");
}
public void lock(E entity, LockMode lockMode) {
LOG.entering(CLASS_NAME, "lock", new Object[] { entity, lockMode });
getHibernateTemplate().lock(entity, lockMode);
LOG.exiting(CLASS_NAME, "lock");
}
public void saveOrUpdateAll(Collection<E> entities) {
getHibernateTemplate().saveOrUpdateAll(entities);
}
@SuppressWarnings("unchecked")
public E merge(E entity) {
LOG.entering(CLASS_NAME, "merge", entity);
E persistentEntity = (E) getHibernateTemplate().merge(entity);
LOG.exiting(CLASS_NAME, "merge", persistentEntity);
return persistentEntity;
}
public void refresh(E entity) {
LOG.entering(CLASS_NAME, "refresh", entity);
getHibernateTemplate().refresh(entity);
LOG.exiting(CLASS_NAME, "refresh");
}
public Long save(E entity) {
LOG.entering(CLASS_NAME, "save", entity);
LOG.exiting(CLASS_NAME, "save");
return (Long) getHibernateTemplate().save(entity);
}
public void saveOrUpdate(E entity) {
LOG.entering(CLASS_NAME, "saveOrUpdate", entity);
getHibernateTemplate().saveOrUpdate(entity);
LOG.exiting(CLASS_NAME, "saveOrUpdate");
}
public void update(E entity) {
LOG.entering(CLASS_NAME, "update", entity);
getHibernateTemplate().update(entity);
LOG.exiting(CLASS_NAME, "update");
}
/**
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
setStaticApplicationContext(applicationContext);
}
private static void setStaticApplicationContext(ApplicationContext applicationContext) {
_applicationContext = applicationContext;
}
/**
* @param queryName
* @return count
*/
protected int getCounter(String queryName) {
@SuppressWarnings("unchecked")
List<Number> counterList = getHibernateTemplate().findByNamedQuery(queryName);
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
/**
* @param queryName
* @param paramName
* @param value
* @return count
*/
protected int getCounter(String queryName, String paramName, Object value) {
@SuppressWarnings("unchecked")
List<Number> counterList = getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramName, value);
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
/**
* @param queryName
* @param paramNames
* @param values
* @return count
*/
protected int getCounter(String queryName, String[] paramNames, Object[] values) {
@SuppressWarnings("unchecked")
List<Number> counterList = getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values);
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
public List<E> narrowSearch(String keyword) {
List<E> result = Collections.EMPTY_LIST;
if (StringUtils.isBlank(keyword)) {
return result;
}
try {
Method method = _entityClass.getMethod("SEARCHABLE_FIELDS");
if (method == null) {
throw new RuntimeException(_entityClass + " should respond to static method call - SEARCHABLE_FIELDS");
}
result = narrowSearch(keyword, (String[]) method.invoke(null, null), _entityClass);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public List<E> search(String keyword) {
List<E> result = Collections.EMPTY_LIST;
if (StringUtils.isBlank(keyword)) {
return result;
}
try {
Method method = _entityClass.getMethod("SEARCHABLE_FIELDS");
if (method == null) {
throw new RuntimeException(_entityClass + " should respond to static method call - SEARCHABLE_FIELDS");
}
result = search(keyword, (String[]) method.invoke(null, null), _entityClass);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
private List<E> search(String keyword, String[] fields, Class clazz) {
Map<String, Integer> paginationOptions = Application.getPaginationOptions();
Integer pageNumber = Integer.valueOf(1);
Integer perPage = Integer.valueOf(5);
if (paginationOptions.containsKey("perPage")) {
pageNumber = paginationOptions.get("pageNumber");
perPage = paginationOptions.get("perPage");
}
FullTextSession fullTextSession = Search.getFullTextSession(getHibernateTemplate().getSessionFactory().getCurrentSession());
// create native Lucene query
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
org.apache.lucene.search.Query query;
try {
query = parser.parse(keyword);
// wrap Lucene query in a org.hibernate.Query
org.hibernate.search.FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, clazz);
hibQuery.setFirstResult((pageNumber - 1) * perPage);
hibQuery.setMaxResults(perPage);
Application.setResultSize(hibQuery.getResultSize());
// execute search
return hibQuery.list();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private List<E> narrowSearch(String keyword, String[] fields, Class clazz) {
/**
* Need to identify better way of doing this for performance reasons.
*/
List<E> results = new ArrayList<E>();
for (String word : keyword.split(" ")) {
if (results.isEmpty()) {
results.addAll(search(word, fields, clazz));
} else {
results.retainAll(search(word, fields, clazz));
}
}
return results;
}
protected static <T extends AbstractDAO<?>> T getDAO(String beanName, Class<T> clazz) {
return clazz.cast(_applicationContext.getBean(beanName, clazz));
}
protected int getCount(List<Number> counterList) {
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
@SuppressWarnings("unchecked")
protected List paginateByNamedQueryAndNamedParam(String hqlName, Map<String, Object> params) {
Query namedQuery = getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery(hqlName);
configurePagination(namedQuery);
for (Entry<String, Object> parameter : params.entrySet()) {
if (parameter.getValue() instanceof Collection) {
namedQuery.setParameterList(parameter.getKey(), (Collection) parameter.getValue());
} else if (parameter.getValue() instanceof Object[]) {
namedQuery.setParameterList(parameter.getKey(), (Object[]) parameter.getValue());
} else {
namedQuery.setParameter(parameter.getKey(), parameter.getValue());
}
}
return namedQuery.list();
}
@SuppressWarnings("unchecked")
protected List paginateByNamedQuery(String hqlName) {
Query namedQuery = getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery(hqlName);
configurePagination(namedQuery);
List result = namedQuery.list();
resetPagination(namedQuery);
return result;
}
private void resetPagination(Query namedQuery) {
getHibernateTemplate().setMaxResults(0);
}
private void configurePagination(Query namedQuery) {
Integer pageNumber = Application.getPaginationOptions().get("pageNumber");
Integer perPage = Application.getPaginationOptions().get("perPage");
if (pageNumber != null && pageNumber > 1) {
namedQuery.setFirstResult((pageNumber - 1) * perPage);
}
namedQuery.setMaxResults(perPage == null ? 5 : perPage);
}
}
package com.isavera.hibernate;
导入java.io.Serializable;
导入java.lang.reflect.Method;
导入java.util.ArrayList;
导入java.util.Collection;
导入java.util.Collections;
导入java.util.HashMap;
导入java.util.HashSet;
导入java.util.List;
导入java.util.Map;
导入java.util.Set;
导入java.util.Map.Entry;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入org.apache.commons.lang.StringUtils;
导入org.apache.lucene.analysis.standard.StandardAnalyzer;
导入org.apache.lucene.queryParser.multifiedqueryparser;
导入org.apache.lucene.queryParser.ParseException;
导入org.hibernate.Criteria;
导入org.hibernate.LockMode;
导入org.hibernate.Query;
导入org.hibernate.annotations.Cache;
导入org.hibernate.annotations.cacheconcurrency策略;
导入org.hibernate.criteria.criteria;
导入org.hibernate.search.FullTextSession;
导入org.hibernate.search.search;
导入org.springframework.beans.BeansException;
导入org.springframework.context.ApplicationContext;
导入org.springframework.context.ApplicationContextAware;
导入org.springframework.dao.ConcurrencyFailureException;
导入org.springframework.orm.hibernate3.support.HibernateDaoSupport;
导入org.springframework.transaction.annotation.Transactional;
导入org.springframework.transaction.interceptor.TransactionSpectSupport;
导入com.isavera.actions.utils.Application;
@抑制警告(“串行”)
@交易的
公共抽象类AbstractDAOImpl扩展了HibernateDaoSupport实现了AbstractDAO,ApplicationContextAware{
私有静态最终字符串CLASS_NAME=AbstractDAOImpl.CLASS.getName();
私有静态最终记录器LOG=Logger.getLogger(类名称);
私有静态应用程序上下文\u应用程序上下文;
私有最终类>T getDAO(字符串beanName,类clazz){
返回clazz.cast(_applicationContext.getBean(beanName,clazz));
}
受保护的int getCount(列表计数器列表){
return counterList==null | | counterList.isEmpty()?0:counterList.iterator().next().intValue();
}
@抑制警告(“未选中”)
受保护列表paginateByNamedQueryAndNamedParam(字符串hqlName,映射参数){
查询名称查询=getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery(hqlName);
配置分页(namedQuery);
for(输入参数:params.entrySet()){
if(集合的参数.getValue()实例){
namedQuery.setParameterList(parameter.getKey(),(Collection)parameter.getValue());
}else if(对象[]的参数.getValue()实例){
namedQuery.setParameterList(parameter.getKey(),(Object[])parameter.getValue();
}否则{
namedQuery.setParameter(parameter.getKey(),parameter.getValue());
}
}
返回namedQuery.list();
}
@抑制警告(“未选中”)
受保护列表paginateByNamedQuery(字符串hqlName){
查询名称查询=getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery(hqlName);
配置分页(namedQuery);
List result=namedQuery.List();
重置分页(namedQuery);
返回结果;
}
私有void重置分页(查询名称查询){
getHibernateTemplate().setMaxResults(0);
}
专用void配置分页(查询名称查询){
整数pageNumber=Application.getPaginationOptions().get(“pageNumber”);
整型每页=Application.getPaginationOptions().get(“每页”);
如果(页码!=null&&pageNumber>1){
namedQuery.setFirstResult((页码-1)*每页);
}
namedQuery.setMaxResults(perPage==null?5:perPage);
}
}
Hi,这并不是关于使用泛型dao(我已经找到了hibernate泛型dao,它拥有我想要的所有铃声和口哨)。它更多的是当您需要一个已定义问题的解决方案时,使用正确的模式。这就是为什么我想要一个模式,允许我使用DetachedCriteria类,但通过实例化一个不是来自hibernate api的对象。您好,在这个类中,您将公开这个方法public List get(Criteria…Criteria),它将hibernate api公开给客户端,这是我一直试图解决的问题。我更喜欢使用CriteriaAPI而不是HQL(我从来没有真正喜欢过它)。我相信CriteriaAPI比HQL慢。所以试着用它。
package com.isavera.hibernate;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.criterion.Criterion;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.isavera.actions.utils.Application;
@SuppressWarnings("serial")
@Transactional
public abstract class AbstractDAOImpl<E> extends HibernateDaoSupport implements AbstractDAO<E>, ApplicationContextAware {
private static final String CLASS_NAME = AbstractDAOImpl.class.getName();
private static final Logger LOG = Logger.getLogger(CLASS_NAME);
private static ApplicationContext _applicationContext;
private final Class<? extends E> _entityClass;
/**
* @param entityClass
*/
public AbstractDAOImpl(Class<? extends E> entityClass) {
super();
_entityClass = entityClass;
}
public void delete(E entity) {
LOG.entering(CLASS_NAME, "delete", entity);
getHibernateTemplate().delete(entity);
LOG.exiting(CLASS_NAME, "delete");
}
public void evict(E entity) {
LOG.entering(CLASS_NAME, "evict", entity);
getHibernateTemplate().evict(entity);
LOG.exiting(CLASS_NAME, "evict");
}
public void deleteAll(Collection<E> entities) {
getHibernateTemplate().deleteAll(entities);
}
@SuppressWarnings("unchecked")
public List<E> findByNamedQuery(String queryName) {
return getHibernateTemplate().findByNamedQuery(queryName);
}
@SuppressWarnings("unchecked")
public List<E> findByNamedQueryAndNamedParam(String queryName, String paramName, Object value) {
return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramName, value);
}
@SuppressWarnings("unchecked")
public List<E> findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) {
return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values);
}
public E get(Serializable id) {
LOG.entering(CLASS_NAME, "get", id);
@SuppressWarnings("unchecked")
E entity = (E) getHibernateTemplate().get(_entityClass, id);
LOG.exiting(CLASS_NAME, "get", entity);
return entity;
}
public List<E> get(Criterion... criterion) {
LOG.entering(CLASS_NAME, "get", criterion);
Criteria criteria = getSession().createCriteria(_entityClass);
for (Criterion c : criterion) {
criteria.add(c);
}
@SuppressWarnings("unchecked")
List<E> list = new ArrayList<E>(criteria.list());
LOG.exiting(CLASS_NAME, "get", list);
return list;
}
public boolean isEntityAttached(E entity) {
return getHibernateTemplate().getSessionFactory().getCurrentSession().contains(entity);
}
public E load(Serializable id) {
LOG.entering(CLASS_NAME, "load", id);
@SuppressWarnings("unchecked")
E entity = (E) getHibernateTemplate().load(_entityClass, id);
LOG.exiting(CLASS_NAME, "load", entity);
return entity;
}
public E load(Serializable id, LockMode lockMode) {
LOG.entering(CLASS_NAME, "load", new Object[] { id, lockMode });
@SuppressWarnings("unchecked")
E entity = (E) getHibernateTemplate().load(_entityClass, id, lockMode);
LOG.exiting(CLASS_NAME, "load", entity);
return entity;
}
public void load(E entity, Serializable id) {
LOG.entering(CLASS_NAME, "load", new Object[] { entity, id });
getHibernateTemplate().load(entity, id);
LOG.exiting(CLASS_NAME, "load");
}
public void lock(E entity, LockMode lockMode) {
LOG.entering(CLASS_NAME, "lock", new Object[] { entity, lockMode });
getHibernateTemplate().lock(entity, lockMode);
LOG.exiting(CLASS_NAME, "lock");
}
public void saveOrUpdateAll(Collection<E> entities) {
getHibernateTemplate().saveOrUpdateAll(entities);
}
@SuppressWarnings("unchecked")
public E merge(E entity) {
LOG.entering(CLASS_NAME, "merge", entity);
E persistentEntity = (E) getHibernateTemplate().merge(entity);
LOG.exiting(CLASS_NAME, "merge", persistentEntity);
return persistentEntity;
}
public void refresh(E entity) {
LOG.entering(CLASS_NAME, "refresh", entity);
getHibernateTemplate().refresh(entity);
LOG.exiting(CLASS_NAME, "refresh");
}
public Long save(E entity) {
LOG.entering(CLASS_NAME, "save", entity);
LOG.exiting(CLASS_NAME, "save");
return (Long) getHibernateTemplate().save(entity);
}
public void saveOrUpdate(E entity) {
LOG.entering(CLASS_NAME, "saveOrUpdate", entity);
getHibernateTemplate().saveOrUpdate(entity);
LOG.exiting(CLASS_NAME, "saveOrUpdate");
}
public void update(E entity) {
LOG.entering(CLASS_NAME, "update", entity);
getHibernateTemplate().update(entity);
LOG.exiting(CLASS_NAME, "update");
}
/**
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
setStaticApplicationContext(applicationContext);
}
private static void setStaticApplicationContext(ApplicationContext applicationContext) {
_applicationContext = applicationContext;
}
/**
* @param queryName
* @return count
*/
protected int getCounter(String queryName) {
@SuppressWarnings("unchecked")
List<Number> counterList = getHibernateTemplate().findByNamedQuery(queryName);
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
/**
* @param queryName
* @param paramName
* @param value
* @return count
*/
protected int getCounter(String queryName, String paramName, Object value) {
@SuppressWarnings("unchecked")
List<Number> counterList = getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramName, value);
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
/**
* @param queryName
* @param paramNames
* @param values
* @return count
*/
protected int getCounter(String queryName, String[] paramNames, Object[] values) {
@SuppressWarnings("unchecked")
List<Number> counterList = getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, paramNames, values);
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
public List<E> narrowSearch(String keyword) {
List<E> result = Collections.EMPTY_LIST;
if (StringUtils.isBlank(keyword)) {
return result;
}
try {
Method method = _entityClass.getMethod("SEARCHABLE_FIELDS");
if (method == null) {
throw new RuntimeException(_entityClass + " should respond to static method call - SEARCHABLE_FIELDS");
}
result = narrowSearch(keyword, (String[]) method.invoke(null, null), _entityClass);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public List<E> search(String keyword) {
List<E> result = Collections.EMPTY_LIST;
if (StringUtils.isBlank(keyword)) {
return result;
}
try {
Method method = _entityClass.getMethod("SEARCHABLE_FIELDS");
if (method == null) {
throw new RuntimeException(_entityClass + " should respond to static method call - SEARCHABLE_FIELDS");
}
result = search(keyword, (String[]) method.invoke(null, null), _entityClass);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
private List<E> search(String keyword, String[] fields, Class clazz) {
Map<String, Integer> paginationOptions = Application.getPaginationOptions();
Integer pageNumber = Integer.valueOf(1);
Integer perPage = Integer.valueOf(5);
if (paginationOptions.containsKey("perPage")) {
pageNumber = paginationOptions.get("pageNumber");
perPage = paginationOptions.get("perPage");
}
FullTextSession fullTextSession = Search.getFullTextSession(getHibernateTemplate().getSessionFactory().getCurrentSession());
// create native Lucene query
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
org.apache.lucene.search.Query query;
try {
query = parser.parse(keyword);
// wrap Lucene query in a org.hibernate.Query
org.hibernate.search.FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query, clazz);
hibQuery.setFirstResult((pageNumber - 1) * perPage);
hibQuery.setMaxResults(perPage);
Application.setResultSize(hibQuery.getResultSize());
// execute search
return hibQuery.list();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private List<E> narrowSearch(String keyword, String[] fields, Class clazz) {
/**
* Need to identify better way of doing this for performance reasons.
*/
List<E> results = new ArrayList<E>();
for (String word : keyword.split(" ")) {
if (results.isEmpty()) {
results.addAll(search(word, fields, clazz));
} else {
results.retainAll(search(word, fields, clazz));
}
}
return results;
}
protected static <T extends AbstractDAO<?>> T getDAO(String beanName, Class<T> clazz) {
return clazz.cast(_applicationContext.getBean(beanName, clazz));
}
protected int getCount(List<Number> counterList) {
return counterList == null || counterList.isEmpty() ? 0 : counterList.iterator().next().intValue();
}
@SuppressWarnings("unchecked")
protected List paginateByNamedQueryAndNamedParam(String hqlName, Map<String, Object> params) {
Query namedQuery = getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery(hqlName);
configurePagination(namedQuery);
for (Entry<String, Object> parameter : params.entrySet()) {
if (parameter.getValue() instanceof Collection) {
namedQuery.setParameterList(parameter.getKey(), (Collection) parameter.getValue());
} else if (parameter.getValue() instanceof Object[]) {
namedQuery.setParameterList(parameter.getKey(), (Object[]) parameter.getValue());
} else {
namedQuery.setParameter(parameter.getKey(), parameter.getValue());
}
}
return namedQuery.list();
}
@SuppressWarnings("unchecked")
protected List paginateByNamedQuery(String hqlName) {
Query namedQuery = getHibernateTemplate().getSessionFactory().getCurrentSession().getNamedQuery(hqlName);
configurePagination(namedQuery);
List result = namedQuery.list();
resetPagination(namedQuery);
return result;
}
private void resetPagination(Query namedQuery) {
getHibernateTemplate().setMaxResults(0);
}
private void configurePagination(Query namedQuery) {
Integer pageNumber = Application.getPaginationOptions().get("pageNumber");
Integer perPage = Application.getPaginationOptions().get("perPage");
if (pageNumber != null && pageNumber > 1) {
namedQuery.setFirstResult((pageNumber - 1) * perPage);
}
namedQuery.setMaxResults(perPage == null ? 5 : perPage);
}
}