Java tutorial
/** * @(#)BaseDao.java 1.0 11:31:14 * Copyright 2015 zxst, Inc. All rights reserved. * attech PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sccl.attech.common.persistence; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.QueryWrapperFilter; import org.apache.lucene.search.Sort; import org.apache.lucene.search.highlight.Formatter; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleFragmenter; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.util.Version; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.internal.CriteriaImpl; import org.hibernate.persister.entity.Loadable; import org.hibernate.search.FullTextQuery; import org.hibernate.search.FullTextSession; import org.hibernate.search.Search; import org.hibernate.search.filter.impl.CachingWrapperFilter; import org.hibernate.search.query.DatabaseRetrievalMethod; import org.hibernate.search.query.ObjectLookupMethod; import org.hibernate.sql.Delete; import org.hibernate.transform.ResultTransformer; import org.hibernate.transform.Transformers; import org.springframework.beans.factory.annotation.Autowired; import org.wltea.analyzer.lucene.IKAnalyzer; import com.sccl.attech.common.utils.Reflections; import com.sccl.attech.common.utils.StringUtils; /** * DAO? * @author sccl * @version 2013-05-15 * @param <T> */ public class BaseDao<T> { /** * SessionFactory */ @Autowired private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } /** * () */ private Class<?> entityClass; /** * ?? */ public BaseDao() { entityClass = Reflections.getClassGenricType(getClass()); } /** * ? Session */ public Session getSession() { System.out.println(" BaseDao session?session?"); return sessionFactory.getCurrentSession(); } /** * ?? */ public void flush() { getSession().flush(); } /** * ? */ public void clear() { getSession().clear(); } // -------------- QL Query -------------- /** * QL * @param page * @param qlString * @return */ public <E> Page<E> find(Page<E> page, String qlString) { return find1(page, qlString, null); } /** * QL * @param page * @param qlString * @param parameter * @return */ @SuppressWarnings("unchecked") public <E> Page<E> find(Page<E> page, String qlString, Parameter parameter) { // get count if (!page.isDisabled() && !page.isNotCount()) { String countQlString = "select count(*) " + removeSelect(removeOrders(qlString)); // page.setCount(Long.valueOf(createQuery(countQlString, parameter).uniqueResult().toString())); Query query = createQuery(countQlString, parameter); List<Object> list = query.list(); if (list.size() > 0) { page.setCount(Long.valueOf(list.size())); } else { page.setCount(list.size()); } if (page.getCount() < 1) { return page; } } // order by String ql = qlString; if (StringUtils.isNotBlank(page.getOrderBy())) { for (String order : StringUtils.split(page.getOrderBy(), ",")) { String[] o = StringUtils.split(order, " "); //???? String orderStr = o[0]; if (orderStr.split("-")[0].equals("desc")) { ql += " order by " + orderStr.split("-")[1] + " desc "; } else { ql += " order by " + orderStr.split("-")[1] + " asc "; } } } Query query = createQuery(ql, parameter); // set page if (!page.isDisabled()) { query.setFirstResult(page.getFirstResult()); query.setMaxResults(page.getMaxResults()); } page.setList(query.list()); return page; } /** * QL * @param page * @param qlString * @param parameter * @return */ @SuppressWarnings("unchecked") public <E> Page<E> find1(Page<E> page, String qlString, Parameter parameter) { // get count if (!page.isDisabled() && !page.isNotCount()) { String countQlString = "select count(*) " + removeSelect(removeOrders(qlString)); // page.setCount(Long.valueOf(createQuery(countQlString, parameter).uniqueResult().toString())); Query query = createQuery(countQlString, parameter); List<Object> list = query.list(); if (list.size() > 0) { page.setCount(Long.parseLong(String.valueOf(list.get(0)))); } else { page.setCount(list.size()); } if (page.getCount() < 1) { return page; } } // order by String ql = qlString; if (StringUtils.isNotBlank(page.getOrderBy())) { for (String order : StringUtils.split(page.getOrderBy(), ",")) { String[] o = StringUtils.split(order, " "); //???? String orderStr = o[0]; if (orderStr.split("-")[0].equals("desc")) { ql += " order by " + orderStr.split("-")[1] + " desc "; } else { ql += " order by " + orderStr.split("-")[1] + " asc "; } } } Query query = createQuery(ql, parameter); // set page if (!page.isDisabled()) { query.setFirstResult(page.getFirstResult()); query.setMaxResults(page.getMaxResults()); } page.setList(query.list()); return page; } /** * QL * @param qlString * @return */ public <E> List<E> find(String qlString) { System.out.println("basedaofind"); return find(qlString, null); } /** * QL () * @param qlString * @return */ public <E> List<E> findrnumber(String qlString, Integer maxresult) { Query query = createQuery(qlString, null); query.setFirstResult(0); query.setMaxResults(maxresult); return query.list(); } /** * QL * @param qlString * @param parameter * @return */ @SuppressWarnings("unchecked") public <E> List<E> find(String qlString, Parameter parameter) { System.out.println("basedaocreate1"); Query query = createQuery(qlString, parameter); System.out.println("basedaocreate2"); if (query.list() == null) System.out.println("?----"); return query.list(); } /** * QL * @return */ @SuppressWarnings("unchecked") public List<T> findAll() { return getSession().createCriteria(entityClass).list(); } /** * ? * @param id * @return */ @SuppressWarnings("unchecked") public T get(Serializable id) { return (T) getSession().get(entityClass, id); } /** * * @param t */ public void removeCache(T t) { getSession().evict(t); } /** * ?new * @param t */ public void merge(T t) { getSession().merge(t); } /** * ?new * @param list */ public void merge(List<T> list) { for (T t : list) { getSession().merge(t); } } /** * ? * @param qlString * @return */ public T getByHql(String qlString) { return getByHql(qlString, null); } /** * ? * @param qlString * @param parameter * @return */ @SuppressWarnings("unchecked") public T getByHql(String qlString, Parameter parameter) { Query query = createQuery(qlString, parameter); return (T) query.uniqueResult(); } /** * ? * @param entity */ public void save(T entity) { try { // ?? Object id = null; for (Method method : entity.getClass().getMethods()) { Id idAnn = method.getAnnotation(Id.class); if (idAnn != null) { id = method.invoke(entity); break; } } // ?? if (StringUtils.isBlank((String) id)) { for (Method method : entity.getClass().getMethods()) { PrePersist pp = method.getAnnotation(PrePersist.class); if (pp != null) { method.invoke(entity); break; } } } // ? else { for (Method method : entity.getClass().getMethods()) { PreUpdate pu = method.getAnnotation(PreUpdate.class); if (pu != null) { method.invoke(entity); break; } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } getSession().saveOrUpdate(entity); //System.out.println(getSession().getIdentifier(entity)); } /** * ?uuid * @param entity */ public String saveRet(T entity) { try { // ?? Object id = null; for (Method method : entity.getClass().getMethods()) { Id idAnn = method.getAnnotation(Id.class); if (idAnn != null) { id = method.invoke(entity); break; } } // ?? if (StringUtils.isBlank((String) id)) { for (Method method : entity.getClass().getMethods()) { PrePersist pp = method.getAnnotation(PrePersist.class); if (pp != null) { method.invoke(entity); break; } } } // ? else { for (Method method : entity.getClass().getMethods()) { PreUpdate pu = method.getAnnotation(PreUpdate.class); if (pu != null) { method.invoke(entity); break; } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } getSession().saveOrUpdate(entity); return (String) getSession().getIdentifier(entity); } /** * ? * @param entity */ public void updateOnly(T entity) { getSession().update(entity); } /** * ?? * @param entity */ public void saveOnly(T entity) { try { // ?? Object id = null; for (Method method : entity.getClass().getMethods()) { Id idAnn = method.getAnnotation(Id.class); if (idAnn != null) { id = method.invoke(entity); break; } } // ?? if (StringUtils.isBlank((String) id)) { for (Method method : entity.getClass().getMethods()) { PrePersist pp = method.getAnnotation(PrePersist.class); if (pp != null) { method.invoke(entity); break; } } } // ? else { for (Method method : entity.getClass().getMethods()) { PreUpdate pu = method.getAnnotation(PreUpdate.class); if (pu != null) { method.invoke(entity); break; } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } getSession().save(entity); } /** * ? * @param entityList */ public void save(List<T> entityList) { for (T entity : entityList) { save(entity); } } /** * * @param qlString * @return */ public int update(String qlString) { return update(qlString, null); } /** * * @param qlString * @param parameter * @return */ public int update(String qlString, Parameter parameter) { return createQuery(qlString, parameter).executeUpdate(); } /** * * @param id * @return */ public int deleteById(Serializable id) { return update("update " + entityClass.getSimpleName() + " set delFlag='" + BaseEntity.DEL_FLAG_DELETE + "' where id = :p1", new Parameter(id)); } @SuppressWarnings("unchecked") public T load(Serializable id) { T t = null; try { t = (T) getSession().load(entityClass, id); } catch (Exception e) { } return t; } /** * ? * @param id * @return */ public void deleteForId(Serializable id) { T t = load(id); getSession().delete(t); } /** * * @param id * @param likeParentIds * @return */ public int deleteById(Serializable id, String likeParentIds) { return update("update " + entityClass.getSimpleName() + " set delFlag = '" + BaseEntity.DEL_FLAG_DELETE + "' where id = :p1 or parentIds like :p2", new Parameter(id, likeParentIds)); } /** * * @param id * @param delFlag * @return */ public int updateDelFlag(Serializable id, String delFlag) { return update("update " + entityClass.getSimpleName() + " set delFlag = :p2 where id = :p1", new Parameter(id, delFlag)); } /** * QL * @param qlString * @param parameter * @return */ public Query createQuery(String qlString, Parameter parameter) { System.out.println("createQuery1?"); Query query = getSession().createQuery(qlString); System.out.println("createQuery2?"); setParameter(query, parameter); return query; } // -------------- SQL Query -------------- /** * SQL * @param page * @param sqlString * @return */ public <E> Page<E> findBySql(Page<E> page, String sqlString) { return findBySql(page, sqlString, null, null); } /** * SQL () * @param page * @param sqlString * @return */ public Page<Object> findBySql2(Page<Object> page, String sqlString) { return findBySql(page, sqlString, null, null); } /** * SQL * @param page * @param sqlString * @param parameter * @return */ public <E> Page<E> findBySql(Page<E> page, String sqlString, Parameter parameter) { return findBySql(page, sqlString, parameter, null); } /** * SQL * @param page * @param sqlString * @param resultClass * @return */ public <E> Page<E> findBySql(Page<E> page, String sqlString, Class<?> resultClass) { return findBySql(page, sqlString, null, resultClass); } /** * SQL * @param page * @param sqlString * @param resultClass * @param parameter * @return */ @SuppressWarnings("unchecked") public <E> Page<E> findBySql(Page<E> page, String sqlString, Parameter parameter, Class<?> resultClass) { // get count if (!page.isDisabled() && !page.isNotCount()) { String countSqlString = "select count(*) " + removeSelect(removeOrders(sqlString)); // page.setCount(Long.valueOf(createSqlQuery(countSqlString, parameter).uniqueResult().toString())); Query query = createSqlQuery(countSqlString, parameter); List<Object> list = query.list(); if (list.size() > 0) { page.setCount(Long.valueOf(list.get(0).toString())); } else { page.setCount(list.size()); } if (page.getCount() < 1) { return page; } } // order by String sql = sqlString; if (StringUtils.isNotBlank(page.getOrderBy())) { for (String order : StringUtils.split(page.getOrderBy(), ",")) { String[] o = StringUtils.split(order, " "); //???? String orderStr = o[0]; if (orderStr.split("-")[0].equals("desc")) { sql += " order by " + orderStr.split("-")[1] + " desc "; } else { sql += " order by " + orderStr.split("-")[1] + " asc "; } } } SQLQuery query = createSqlQuery(sql, parameter); // set page if (!page.isDisabled()) { query.setFirstResult(page.getFirstResult()); query.setMaxResults(page.getMaxResults()); } System.out.println(sql); setResultTransformer(query, resultClass); page.setList(query.list()); return page; } /** * SQL * @param sqlString * @return */ public <E> List<E> findBySql(String sqlString) { return findBySql(sqlString, null, null); } /** * SQL * @param sqlString * @param parameter * @return */ public <E> List<E> findBySql(String sqlString, Parameter parameter) { return findBySql(sqlString, parameter, null); } /** * SQL * @param sqlString * @param resultClass * @return */ public <E> List<E> findBySql(String sqlString, Class<?> resultClass) { return findBySql(sqlString, null, resultClass); } /** * SQL * @param sqlString * @param resultClass * @param parameter * @return */ @SuppressWarnings("unchecked") public <E> List<E> findBySql(String sqlString, Parameter parameter, Class<?> resultClass) { SQLQuery query = createSqlQuery(sqlString, parameter); setResultTransformer(query, resultClass); return query.list(); } /** * SQL * @param sqlString * @param parameter * @return */ public int updateBySql(String sqlString, Parameter parameter) { return createSqlQuery(sqlString, parameter).executeUpdate(); } /** * SQL * @param sqlString * @param parameter * @return */ public int updateBySql(String sqlString) { return createSqlQuery(sqlString, null).executeUpdate(); } /** * SQL * @param sqlString * @param parameter * @return */ public SQLQuery createSqlQuery(String sqlString, Parameter parameter) { SQLQuery query = getSession().createSQLQuery(sqlString); setParameter(query, parameter); return query; } // -------------- Query Tools -------------- /** * * @param query * @param resultClass */ private void setResultTransformer(SQLQuery query, Class<?> resultClass) { if (resultClass != null) { if (resultClass == Map.class) { query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); } else if (resultClass == List.class) { query.setResultTransformer(Transformers.TO_LIST); } else { query.addEntity(resultClass); } } } /** * ? * @param query * @param parameter */ private void setParameter(Query query, Parameter parameter) { if (parameter != null) { Set<String> keySet = parameter.keySet(); for (String string : keySet) { Object value = parameter.get(string); //????? if (value instanceof Collection<?>) { query.setParameterList(string, (Collection<?>) value); } else if (value instanceof Object[]) { query.setParameterList(string, (Object[]) value); } else { query.setParameter(string, value); } } } } /** * qlStringselect?? * @param qlString * @return */ private String removeSelect(String qlString) { int beginPos = qlString.toLowerCase().indexOf("from"); return qlString.substring(beginPos); } /** * hqlorderBy?? * @param qlString * @return */ private String removeOrders(String qlString) { Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(qlString); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, ""); } m.appendTail(sb); return sb.toString(); } // -------------- Criteria -------------- /** * * @param page * @return */ public Page<T> find(Page<T> page) { return find(page, createDetachedCriteria()); } /** * * @param page * @param detachedCriteria * @return */ public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria) { return find(page, detachedCriteria, Criteria.DISTINCT_ROOT_ENTITY); } /** * * @param page * @param detachedCriteria * @param resultTransformer * @return */ @SuppressWarnings("unchecked") public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) { // get count if (!page.isDisabled() && !page.isNotCount()) { page.setCount(count(detachedCriteria)); if (page.getCount() < 1) { return page; } } Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); criteria.setResultTransformer(resultTransformer); // set page if (!page.isDisabled()) { criteria.setFirstResult(page.getFirstResult()); criteria.setMaxResults(page.getMaxResults()); } // order by if (StringUtils.isNotBlank(page.getOrderBy())) { for (String order : StringUtils.split(page.getOrderBy(), ",")) { String[] o = StringUtils.split(order, " "); //???? String orderStr = o[0]; if (orderStr.split("-")[0].equals("desc")) { criteria.addOrder(Order.desc(orderStr.split("-")[1])); } else { criteria.addOrder(Order.asc(orderStr.split("-")[1])); } } } page.setList(criteria.list()); return page; } /** * * @param detachedCriteria * @return */ public List<T> find(DetachedCriteria detachedCriteria) { return find(detachedCriteria, Criteria.DISTINCT_ROOT_ENTITY); } /** * * @param detachedCriteria * @param resultTransformer * @return */ @SuppressWarnings("unchecked") public List<T> find(DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) { Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); criteria.setResultTransformer(resultTransformer); return criteria.list(); } /** * * @param detachedCriteria * @return */ @SuppressWarnings("rawtypes") public long count(DetachedCriteria detachedCriteria) { Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); long totalCount = 0; try { // Get orders Field field = CriteriaImpl.class.getDeclaredField("orderEntries"); field.setAccessible(true); List orderEntrys = (List) field.get(criteria); // Remove orders field.set(criteria, new ArrayList()); // Get count criteria.setProjection(Projections.rowCount()); totalCount = Long.valueOf(criteria.uniqueResult().toString()); // Clean count criteria.setProjection(null); // Restore orders field.set(criteria, orderEntrys); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return totalCount; } /** * ? * @param criterions Restrictions.eq("name", value); * @return */ public DetachedCriteria createDetachedCriteria(Criterion... criterions) { DetachedCriteria dc = DetachedCriteria.forClass(entityClass); for (Criterion c : criterions) { dc.add(c); } return dc; } // -------------- Hibernate search -------------- /** * ?Session */ public FullTextSession getFullTextSession() { return Search.getFullTextSession(getSession()); } /** * */ public void createIndex() { try { getFullTextSession().createIndexer(entityClass).startAndWait(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * * @param page * @param query * @param queryFilter * @param sort ? * @return */ @SuppressWarnings("unchecked") public Page<T> search(Page<T> page, BooleanQuery query, BooleanQuery queryFilter, Sort sort) { // FullTextQuery fullTextQuery = getFullTextSession().createFullTextQuery(query, entityClass); // if (queryFilter != null) { fullTextQuery.setFilter(new CachingWrapperFilter(new QueryWrapperFilter(queryFilter))); } // ? if (sort != null) { fullTextQuery.setSort(sort); } // page.setCount(fullTextQuery.getResultSize()); fullTextQuery.setFirstResult(page.getFirstResult()); fullTextQuery.setMaxResults(page.getMaxResults()); // ?? fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SECOND_LEVEL_CACHE, DatabaseRetrievalMethod.QUERY); // page.setList(fullTextQuery.list()); return page; } /** * ? */ public BooleanQuery getFullTextQuery(BooleanClause... booleanClauses) { BooleanQuery booleanQuery = new BooleanQuery(); for (BooleanClause booleanClause : booleanClauses) { booleanQuery.add(booleanClause); } return booleanQuery; } /** * ? * @param q * @param fields * @return */ public BooleanQuery getFullTextQuery(String q, String... fields) { Analyzer analyzer = new IKAnalyzer(); BooleanQuery query = new BooleanQuery(); try { if (StringUtils.isNotBlank(q)) { for (String field : fields) { QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer); query.add(parser.parse(q), Occur.SHOULD); } } } catch (ParseException e) { e.printStackTrace(); } return query; } /** * * @param query * @param list * @param subLength ? * @param fields ?? */ public List<T> keywordsHighlight(BooleanQuery query, List<T> list, int subLength, String... fields) { Analyzer analyzer = new IKAnalyzer(); Formatter formatter = new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>"); Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query)); highlighter.setTextFragmenter(new SimpleFragmenter(subLength)); for (T entity : list) { try { for (String field : fields) { String text = StringUtils.replaceHtml((String) Reflections.invokeGetter(entity, field)); String description = highlighter.getBestFragment(analyzer, field, text); if (description != null) { Reflections.invokeSetter(entity, fields[0], description); break; } Reflections.invokeSetter(entity, fields[0], StringUtils.abbr(text, subLength * 2)); } } catch (IOException e) { e.printStackTrace(); } catch (InvalidTokenOffsetsException e) { e.printStackTrace(); } } return list; } /** * Map by sql. * ?sql map list * @param sql * the sql * @param parameter * the parameter * @return the list */ public List<Map<String, Object>> mapBySql(String sql, Parameter parameter) { Query query = createSqlQuery(sql, parameter); query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); return query.list(); } }