PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/persistence/src/main/java/org/yes/cart/dao/impl/GenericDAOHibernateImpl.java

http://yes-cart.googlecode.com/
Java | 563 lines | 367 code | 65 blank | 131 comment | 46 complexity | 8f7e8d8211c5a12d0dcc7fef9ea53482 MD5 | raw file
  1. package org.yes.cart.dao.impl;
  2. import org.apache.lucene.search.SortField;
  3. import org.hibernate.*;
  4. import org.hibernate.criterion.Criterion;
  5. import org.hibernate.criterion.Example;
  6. import org.hibernate.search.FullTextQuery;
  7. import org.hibernate.search.FullTextSession;
  8. import org.hibernate.search.Search;
  9. import org.hibernate.search.util.impl.HibernateHelper;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.yes.cart.dao.CriteriaTuner;
  13. import org.yes.cart.dao.EntityFactory;
  14. import org.yes.cart.dao.GenericDAO;
  15. import org.yes.cart.util.ShopCodeContext;
  16. import java.io.Serializable;
  17. import java.util.Collection;
  18. import java.util.Collections;
  19. import java.util.List;
  20. /**
  21. * User: Igor Azarny iazarny@yahoo.com
  22. * Date: 08-May-2011
  23. * Time: 11:12:54
  24. */
  25. public class GenericDAOHibernateImpl<T, PK extends Serializable>
  26. implements GenericDAO<T, PK> {
  27. private static final Logger LOG = LoggerFactory.getLogger(ShopCodeContext.getShopCode());
  28. final private Class<T> persistentClass;
  29. final private EntityFactory entityFactory;
  30. private SessionFactory sessionFactory;
  31. /**
  32. * Set the Hibernate SessionFactory to be used by this DAO.
  33. * Will automatically create a HibernateTemplate for the given SessionFactory.
  34. */
  35. public final void setSessionFactory(final SessionFactory sessionFactory) {
  36. this.sessionFactory = sessionFactory;
  37. }
  38. /**
  39. * Default constructor.
  40. *
  41. * @param type - entity type
  42. * @param entityFactory {@link EntityFactory} to create the entities
  43. */
  44. @SuppressWarnings("unchecked")
  45. public GenericDAOHibernateImpl(
  46. final Class<T> type,
  47. final EntityFactory entityFactory) {
  48. this.persistentClass = type;
  49. this.entityFactory = entityFactory;
  50. }
  51. /**
  52. * {@inheritDoc}
  53. */
  54. public EntityFactory getEntityFactory() {
  55. return entityFactory;
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. public T findById(PK id) {
  61. return findById(id, false);
  62. }
  63. /**
  64. * {@inheritDoc}
  65. */
  66. @SuppressWarnings("unchecked")
  67. public T findById(final PK id, final boolean lock) {
  68. T entity;
  69. if (lock) {
  70. entity = (T) sessionFactory.getCurrentSession().get(getPersistentClass(), id, LockMode.UPGRADE);
  71. } else {
  72. entity = (T) sessionFactory.getCurrentSession().get(getPersistentClass(), id);
  73. }
  74. return entity;
  75. }
  76. /**
  77. * {@inheritDoc}
  78. */
  79. @SuppressWarnings("unchecked")
  80. public List<T> findByExample(final T exampleInstance, final String[] excludeProperty) {
  81. Criteria crit = sessionFactory.getCurrentSession().createCriteria(getPersistentClass());
  82. Example example = Example.create(exampleInstance);
  83. for (String exclude : excludeProperty) {
  84. example.excludeProperty(exclude);
  85. }
  86. crit.add(example);
  87. return crit.list();
  88. }
  89. /**
  90. * {@inheritDoc}
  91. */
  92. @SuppressWarnings("unchecked")
  93. public <T> T findSingleByNamedQuery(final String namedQueryName, final Object... parameters) {
  94. List<T> rez = (List<T>) this.findByNamedQuery(namedQueryName, parameters);
  95. if (!rez.isEmpty()) {
  96. return rez.get(0);
  97. }
  98. return null;
  99. }
  100. /**
  101. * {@inheritDoc}
  102. */
  103. public Object getScalarResultByNamedQuery(final String namedQueryName, final Object... parameters) {
  104. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  105. int idx = 1;
  106. for (Object param : parameters) {
  107. query.setParameter(String.valueOf(idx), param);
  108. idx++;
  109. }
  110. return query.uniqueResult();
  111. }
  112. /**
  113. * {@inheritDoc}
  114. */
  115. public Object findSingleByQuery(final String hsqlQuery, final Object... parameters) {
  116. Query query = sessionFactory.getCurrentSession().createQuery(hsqlQuery);
  117. int idx = 1;
  118. for (Object param : parameters) {
  119. query.setParameter(String.valueOf(idx), param);
  120. idx++;
  121. }
  122. final List rez = query.list();
  123. int size = rez.size();
  124. switch (size) {
  125. case 0: {
  126. return null;
  127. }
  128. case 1: {
  129. return rez.get(0);
  130. }
  131. default: {
  132. LOG.error("#findSingleByQuery has more than one result for " + hsqlQuery);
  133. return rez.get(0);
  134. }
  135. }
  136. }
  137. /**
  138. * {@inheritDoc}
  139. */
  140. @SuppressWarnings("unchecked")
  141. public List<T> findByNamedQuery(final String namedQueryName, final Object... parameters) {
  142. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  143. if (parameters != null) {
  144. int idx = 1;
  145. for (Object param : parameters) {
  146. query.setParameter(String.valueOf(idx), param);
  147. idx++;
  148. }
  149. }
  150. return query.list();
  151. }
  152. /**
  153. * {@inheritDoc}
  154. */
  155. @SuppressWarnings("unchecked")
  156. public List<Object> findQueryObjectByNamedQuery(final String namedQueryName, final Object... parameters) {
  157. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  158. int idx = 1;
  159. if (parameters != null) {
  160. for (Object param : parameters) {
  161. query.setParameter(String.valueOf(idx), param);
  162. idx++;
  163. }
  164. }
  165. return query.list();
  166. }
  167. /**
  168. * {@inheritDoc}
  169. */
  170. @SuppressWarnings("unchecked")
  171. public List<Object[]> findQueryObjectsByNamedQuery(final String namedQueryName, final Object... parameters) {
  172. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  173. int idx = 1;
  174. if (parameters != null) {
  175. for (Object param : parameters) {
  176. query.setParameter(String.valueOf(idx), param);
  177. idx++;
  178. }
  179. }
  180. return query.list();
  181. }
  182. /**
  183. * {@inheritDoc}
  184. */
  185. @SuppressWarnings("unchecked")
  186. public List<Object[]> findQueryObjectsByNamedQueryWithList(final String namedQueryName, final List parameter) {
  187. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  188. query.setParameterList("list", parameter);
  189. return query.list();
  190. }
  191. /**
  192. * {@inheritDoc}
  193. */
  194. @SuppressWarnings("unchecked")
  195. public List<T> findQueryObjectsByNamedQueryWithList(
  196. final String namedQueryName, final Collection<Object> listParameter,
  197. final Object... parameters) {
  198. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  199. query.setParameterList("list", listParameter);
  200. int idx = 1;
  201. if (parameters != null) {
  202. for (Object param : parameters) {
  203. query.setParameter(String.valueOf(idx), param);
  204. idx++;
  205. }
  206. }
  207. return query.list();
  208. }
  209. /**
  210. * {@inheritDoc}
  211. */
  212. @SuppressWarnings("unchecked")
  213. public List<T> findRangeByNamedQuery(final String namedQueryName,
  214. final int firtsResult,
  215. final int maxResults,
  216. final Object... parameters) {
  217. Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  218. query.setFirstResult(firtsResult);
  219. query.setMaxResults(maxResults);
  220. int idx = 1;
  221. for (Object param : parameters) {
  222. query.setParameter(String.valueOf(idx), param);
  223. idx++;
  224. }
  225. return query.list();
  226. }
  227. /**
  228. * {@inheritDoc}
  229. */
  230. @SuppressWarnings("unchecked")
  231. public List<T> findAll() {
  232. return findByCriteria();
  233. }
  234. /**
  235. * {@inheritDoc}
  236. */
  237. @SuppressWarnings("unchecked")
  238. public T saveOrUpdate(T entity) {
  239. sessionFactory.getCurrentSession().saveOrUpdate(entity);
  240. return entity;
  241. }
  242. /**
  243. * {@inheritDoc}
  244. */
  245. @SuppressWarnings("unchecked")
  246. public T create(T entity) {
  247. sessionFactory.getCurrentSession().save(entity);
  248. return entity;
  249. }
  250. /**
  251. * {@inheritDoc}
  252. */
  253. @SuppressWarnings("unchecked")
  254. public T update(T entity) {
  255. sessionFactory.getCurrentSession().update(entity);
  256. return entity;
  257. }
  258. /**
  259. * {@inheritDoc}
  260. */
  261. public void delete(T entity) {
  262. sessionFactory.getCurrentSession().delete(entity);
  263. }
  264. /**
  265. * {@inheritDoc}
  266. */
  267. @SuppressWarnings("unchecked")
  268. public List<T> findByCriteria(Criterion... criterion) {
  269. Criteria crit = sessionFactory.getCurrentSession().createCriteria(getPersistentClass());
  270. for (Criterion c : criterion) {
  271. crit.add(c);
  272. }
  273. return crit.list();
  274. }
  275. /**
  276. * {@inheritDoc}
  277. */
  278. public T findSingleByCriteria(final Criterion... criterion) {
  279. return findSingleByCriteria(null, criterion);
  280. }
  281. /**
  282. * {@inheritDoc}
  283. */
  284. public T findSingleByCriteria(final CriteriaTuner criteriaTuner, final Criterion... criterion) {
  285. Criteria crit = sessionFactory.getCurrentSession().createCriteria(getPersistentClass());
  286. for (Criterion c : criterion) {
  287. crit.add(c);
  288. }
  289. if (criteriaTuner != null) {
  290. criteriaTuner.tune(crit);
  291. }
  292. return (T) crit.uniqueResult();
  293. }
  294. private Class<T> getPersistentClass() {
  295. return persistentClass;
  296. }
  297. /**
  298. * Check is entity need to be in index.
  299. *
  300. * @param entity entity to check
  301. * @return true if entity need to be in lucene index.
  302. */
  303. protected boolean isIncludeInLuceneIndex(T entity) {
  304. return true;
  305. }
  306. /**
  307. * {@inheritDoc}
  308. */
  309. public final void fullTextSearchPurge(final PK primaryKey) {
  310. FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
  311. fullTextSession.setFlushMode(FlushMode.MANUAL);
  312. fullTextSession.setCacheMode(CacheMode.IGNORE);
  313. fullTextSession.purge(getPersistentClass(), primaryKey);
  314. fullTextSession.flushToIndexes(); //apply changes to indexes
  315. fullTextSession.clear(); //clear since the queue is processed
  316. }
  317. /**
  318. * {@inheritDoc}
  319. */
  320. public int fullTextSearchReindex(final PK primaryKey) {
  321. int result = 0;
  322. if (null != getPersistentClass().getAnnotation(org.hibernate.search.annotations.Indexed.class)) {
  323. sessionFactory.evict(getPersistentClass(), primaryKey);
  324. T entity = findById(primaryKey);
  325. FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
  326. fullTextSession.setFlushMode(FlushMode.MANUAL);
  327. fullTextSession.setCacheMode(CacheMode.IGNORE);
  328. fullTextSession.purge(getPersistentClass(), primaryKey);
  329. fullTextSession.index(HibernateHelper.unproxy(entity));
  330. result++;
  331. fullTextSession.flushToIndexes(); //apply changes to indexes
  332. fullTextSession.clear(); //clear since the queue is processed
  333. }
  334. return result;
  335. }
  336. /**
  337. * {@inheritDoc}
  338. */
  339. public int fullTextSearchReindex() {
  340. final int BATCH_SIZE = 20;
  341. int index = 0;
  342. if (null != getPersistentClass().getAnnotation(org.hibernate.search.annotations.Indexed.class)) {
  343. FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
  344. fullTextSession.setFlushMode(FlushMode.MANUAL);
  345. fullTextSession.setCacheMode(CacheMode.IGNORE);
  346. fullTextSession.purgeAll(getPersistentClass());
  347. fullTextSession.getSearchFactory().optimize(getPersistentClass());
  348. // Transaction tx = fullTextSession.beginTransaction();
  349. ScrollableResults results = fullTextSession.createCriteria(persistentClass)
  350. .setFetchSize(BATCH_SIZE)
  351. .scroll(ScrollMode.FORWARD_ONLY);
  352. while (results.next()) {
  353. index++;
  354. T entity = (T) results.get(0);
  355. fullTextSession.index(HibernateHelper.unproxy(entity)); //index each element
  356. if (index % BATCH_SIZE == 0) {
  357. fullTextSession.flushToIndexes(); //apply changes to indexes
  358. fullTextSession.clear(); //clear since the queue is processed
  359. if (LOG.isInfoEnabled()) {
  360. LOG.info("Indexed " + index + " items of " + persistentClass + " class");
  361. }
  362. }
  363. }
  364. fullTextSession.flushToIndexes(); //apply changes to indexes
  365. fullTextSession.clear(); //clear since the queue is processed
  366. //tx.commit();
  367. }
  368. return index;
  369. }
  370. /**
  371. * {@inheritDoc}
  372. */
  373. @SuppressWarnings("unchecked")
  374. public List<T> fullTextSearch(final org.apache.lucene.search.Query query) {
  375. if (null != getPersistentClass().getAnnotation(org.hibernate.search.annotations.Indexed.class)) {
  376. FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
  377. Query fullTextQuery = fullTextSession.createFullTextQuery(query, getPersistentClass());
  378. List<T> list = fullTextQuery.list();
  379. if (list != null) {
  380. return list;
  381. }
  382. }
  383. return Collections.EMPTY_LIST;
  384. }
  385. /**
  386. * {@inheritDoc}
  387. */
  388. @SuppressWarnings("unchecked")
  389. public List<T> fullTextSearch(final org.apache.lucene.search.Query query,
  390. final int firtsResult,
  391. final int maxResults) {
  392. return fullTextSearch(query, firtsResult, maxResults, null);
  393. }
  394. /**
  395. * {@inheritDoc}
  396. */
  397. @SuppressWarnings("unchecked")
  398. public List<T> fullTextSearch(final org.apache.lucene.search.Query query,
  399. final int firtsResult,
  400. final int maxResults,
  401. final String sortFieldName) {
  402. return fullTextSearch(query, firtsResult, maxResults, sortFieldName, false);
  403. }
  404. /**
  405. * {@inheritDoc}
  406. */
  407. @SuppressWarnings("unchecked")
  408. public List<T> fullTextSearch(final org.apache.lucene.search.Query query,
  409. final int firtsResult,
  410. final int maxResults,
  411. final String sortFieldName,
  412. final boolean reverse) {
  413. if (null != getPersistentClass().getAnnotation(org.hibernate.search.annotations.Indexed.class)) {
  414. FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
  415. FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, getPersistentClass());
  416. if (sortFieldName != null) {
  417. org.apache.lucene.search.Sort sort = new org.apache.lucene.search.Sort(
  418. new org.apache.lucene.search.SortField(sortFieldName, SortField.STRING, reverse));
  419. fullTextQuery.setSort(sort);
  420. }
  421. fullTextQuery.setFirstResult(firtsResult);
  422. fullTextQuery.setMaxResults(maxResults);
  423. List<T> list = fullTextQuery.list();
  424. if (list != null) {
  425. return list;
  426. }
  427. }
  428. return Collections.EMPTY_LIST;
  429. }
  430. /**
  431. * {@inheritDoc}
  432. */
  433. public int getResultCount(final org.apache.lucene.search.Query query) {
  434. FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
  435. return fullTextSession.createFullTextQuery(query, getPersistentClass()).getResultSize();
  436. }
  437. /**
  438. * {@inheritDoc}
  439. */
  440. public int executeNativeUpdate(final String nativeQuery) {
  441. SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(nativeQuery);
  442. return sqlQuery.executeUpdate();
  443. }
  444. /**
  445. * {@inheritDoc}
  446. */
  447. public List executeNativeQuery(final String nativeQuery) {
  448. SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(nativeQuery);
  449. return sqlQuery.list();
  450. }
  451. /**
  452. * {@inheritDoc}
  453. */
  454. public List executeHsqlQuery(final String hsql) {
  455. Query query = sessionFactory.getCurrentSession().createQuery(hsql);
  456. return query.list();
  457. }
  458. /**
  459. * {@inheritDoc}
  460. */
  461. public int executeHsqlUpdate(final String hsql) {
  462. Query query = sessionFactory.getCurrentSession().createQuery(hsql);
  463. return query.executeUpdate();
  464. }
  465. /**
  466. * {@inheritDoc}
  467. */
  468. public int executeNativeUpdate(final String nativeQuery, final Object... parameters) {
  469. SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(nativeQuery);
  470. int idx = 1;
  471. for (Object param : parameters) {
  472. sqlQuery.setParameter(String.valueOf(idx), param);
  473. idx++;
  474. }
  475. return sqlQuery.executeUpdate();
  476. }
  477. /**
  478. * {@inheritDoc}
  479. */
  480. public int executeUpdate(final String namedQueryName, final Object... parameters) {
  481. final Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName);
  482. int idx = 1;
  483. if (parameters != null) {
  484. for (Object param : parameters) {
  485. query.setParameter(String.valueOf(idx), param);
  486. idx++;
  487. }
  488. }
  489. return query.executeUpdate();
  490. }
  491. /**
  492. * {@inheritDoc}
  493. */
  494. public void flushClear() {
  495. sessionFactory.getCurrentSession().flush();
  496. sessionFactory.getCurrentSession().clear();
  497. }
  498. }