1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17   * SOFTWARE.
18   */
19  
20  package com.liferay.portlet.ratings.service.persistence;
21  
22  import com.liferay.portal.SystemException;
23  import com.liferay.portal.kernel.annotation.BeanReference;
24  import com.liferay.portal.kernel.cache.CacheRegistry;
25  import com.liferay.portal.kernel.dao.orm.DynamicQuery;
26  import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
27  import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
28  import com.liferay.portal.kernel.dao.orm.FinderPath;
29  import com.liferay.portal.kernel.dao.orm.Query;
30  import com.liferay.portal.kernel.dao.orm.QueryPos;
31  import com.liferay.portal.kernel.dao.orm.QueryUtil;
32  import com.liferay.portal.kernel.dao.orm.Session;
33  import com.liferay.portal.kernel.log.Log;
34  import com.liferay.portal.kernel.log.LogFactoryUtil;
35  import com.liferay.portal.kernel.util.GetterUtil;
36  import com.liferay.portal.kernel.util.OrderByComparator;
37  import com.liferay.portal.kernel.util.StringPool;
38  import com.liferay.portal.kernel.util.StringUtil;
39  import com.liferay.portal.model.ModelListener;
40  import com.liferay.portal.service.persistence.BatchSessionUtil;
41  import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
42  
43  import com.liferay.portlet.ratings.NoSuchStatsException;
44  import com.liferay.portlet.ratings.model.RatingsStats;
45  import com.liferay.portlet.ratings.model.impl.RatingsStatsImpl;
46  import com.liferay.portlet.ratings.model.impl.RatingsStatsModelImpl;
47  
48  import java.util.ArrayList;
49  import java.util.Collections;
50  import java.util.List;
51  
52  /**
53   * <a href="RatingsStatsPersistenceImpl.java.html"><b><i>View Source</i></b></a>
54   *
55   * @author Brian Wing Shun Chan
56   *
57   */
58  public class RatingsStatsPersistenceImpl extends BasePersistenceImpl
59      implements RatingsStatsPersistence {
60      public static final String FINDER_CLASS_NAME_ENTITY = RatingsStatsImpl.class.getName();
61      public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
62          ".List";
63      public static final FinderPath FINDER_PATH_FETCH_BY_C_C = new FinderPath(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
64              RatingsStatsModelImpl.FINDER_CACHE_ENABLED,
65              FINDER_CLASS_NAME_ENTITY, "fetchByC_C",
66              new String[] { Long.class.getName(), Long.class.getName() });
67      public static final FinderPath FINDER_PATH_COUNT_BY_C_C = new FinderPath(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
68              RatingsStatsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
69              "countByC_C",
70              new String[] { Long.class.getName(), Long.class.getName() });
71      public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
72              RatingsStatsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
73              "findAll", new String[0]);
74      public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
75              RatingsStatsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
76              "countAll", new String[0]);
77  
78      public void cacheResult(RatingsStats ratingsStats) {
79          EntityCacheUtil.putResult(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
80              RatingsStatsImpl.class, ratingsStats.getPrimaryKey(), ratingsStats);
81  
82          FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_C,
83              new Object[] {
84                  new Long(ratingsStats.getClassNameId()),
85                  new Long(ratingsStats.getClassPK())
86              }, ratingsStats);
87      }
88  
89      public void cacheResult(List<RatingsStats> ratingsStatses) {
90          for (RatingsStats ratingsStats : ratingsStatses) {
91              if (EntityCacheUtil.getResult(
92                          RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
93                          RatingsStatsImpl.class, ratingsStats.getPrimaryKey(),
94                          this) == null) {
95                  cacheResult(ratingsStats);
96              }
97          }
98      }
99  
100     public void clearCache() {
101         CacheRegistry.clear(RatingsStatsImpl.class.getName());
102         EntityCacheUtil.clearCache(RatingsStatsImpl.class.getName());
103         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
104         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
105     }
106 
107     public RatingsStats create(long statsId) {
108         RatingsStats ratingsStats = new RatingsStatsImpl();
109 
110         ratingsStats.setNew(true);
111         ratingsStats.setPrimaryKey(statsId);
112 
113         return ratingsStats;
114     }
115 
116     public RatingsStats remove(long statsId)
117         throws NoSuchStatsException, SystemException {
118         Session session = null;
119 
120         try {
121             session = openSession();
122 
123             RatingsStats ratingsStats = (RatingsStats)session.get(RatingsStatsImpl.class,
124                     new Long(statsId));
125 
126             if (ratingsStats == null) {
127                 if (_log.isWarnEnabled()) {
128                     _log.warn("No RatingsStats exists with the primary key " +
129                         statsId);
130                 }
131 
132                 throw new NoSuchStatsException(
133                     "No RatingsStats exists with the primary key " + statsId);
134             }
135 
136             return remove(ratingsStats);
137         }
138         catch (NoSuchStatsException nsee) {
139             throw nsee;
140         }
141         catch (Exception e) {
142             throw processException(e);
143         }
144         finally {
145             closeSession(session);
146         }
147     }
148 
149     public RatingsStats remove(RatingsStats ratingsStats)
150         throws SystemException {
151         for (ModelListener<RatingsStats> listener : listeners) {
152             listener.onBeforeRemove(ratingsStats);
153         }
154 
155         ratingsStats = removeImpl(ratingsStats);
156 
157         for (ModelListener<RatingsStats> listener : listeners) {
158             listener.onAfterRemove(ratingsStats);
159         }
160 
161         return ratingsStats;
162     }
163 
164     protected RatingsStats removeImpl(RatingsStats ratingsStats)
165         throws SystemException {
166         Session session = null;
167 
168         try {
169             session = openSession();
170 
171             if (ratingsStats.isCachedModel() || BatchSessionUtil.isEnabled()) {
172                 Object staleObject = session.get(RatingsStatsImpl.class,
173                         ratingsStats.getPrimaryKeyObj());
174 
175                 if (staleObject != null) {
176                     session.evict(staleObject);
177                 }
178             }
179 
180             session.delete(ratingsStats);
181 
182             session.flush();
183         }
184         catch (Exception e) {
185             throw processException(e);
186         }
187         finally {
188             closeSession(session);
189         }
190 
191         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
192 
193         RatingsStatsModelImpl ratingsStatsModelImpl = (RatingsStatsModelImpl)ratingsStats;
194 
195         FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_C_C,
196             new Object[] {
197                 new Long(ratingsStatsModelImpl.getOriginalClassNameId()),
198                 new Long(ratingsStatsModelImpl.getOriginalClassPK())
199             });
200 
201         EntityCacheUtil.removeResult(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
202             RatingsStatsImpl.class, ratingsStats.getPrimaryKey());
203 
204         return ratingsStats;
205     }
206 
207     /**
208      * @deprecated Use <code>update(RatingsStats ratingsStats, boolean merge)</code>.
209      */
210     public RatingsStats update(RatingsStats ratingsStats)
211         throws SystemException {
212         if (_log.isWarnEnabled()) {
213             _log.warn(
214                 "Using the deprecated update(RatingsStats ratingsStats) method. Use update(RatingsStats ratingsStats, boolean merge) instead.");
215         }
216 
217         return update(ratingsStats, false);
218     }
219 
220     /**
221      * Add, update, or merge, the entity. This method also calls the model
222      * listeners to trigger the proper events associated with adding, deleting,
223      * or updating an entity.
224      *
225      * @param        ratingsStats the entity to add, update, or merge
226      * @param        merge boolean value for whether to merge the entity. The
227      *                default value is false. Setting merge to true is more
228      *                expensive and should only be true when ratingsStats is
229      *                transient. See LEP-5473 for a detailed discussion of this
230      *                method.
231      * @return        true if the portlet can be displayed via Ajax
232      */
233     public RatingsStats update(RatingsStats ratingsStats, boolean merge)
234         throws SystemException {
235         boolean isNew = ratingsStats.isNew();
236 
237         for (ModelListener<RatingsStats> listener : listeners) {
238             if (isNew) {
239                 listener.onBeforeCreate(ratingsStats);
240             }
241             else {
242                 listener.onBeforeUpdate(ratingsStats);
243             }
244         }
245 
246         ratingsStats = updateImpl(ratingsStats, merge);
247 
248         for (ModelListener<RatingsStats> listener : listeners) {
249             if (isNew) {
250                 listener.onAfterCreate(ratingsStats);
251             }
252             else {
253                 listener.onAfterUpdate(ratingsStats);
254             }
255         }
256 
257         return ratingsStats;
258     }
259 
260     public RatingsStats updateImpl(
261         com.liferay.portlet.ratings.model.RatingsStats ratingsStats,
262         boolean merge) throws SystemException {
263         boolean isNew = ratingsStats.isNew();
264 
265         RatingsStatsModelImpl ratingsStatsModelImpl = (RatingsStatsModelImpl)ratingsStats;
266 
267         Session session = null;
268 
269         try {
270             session = openSession();
271 
272             BatchSessionUtil.update(session, ratingsStats, merge);
273 
274             ratingsStats.setNew(false);
275         }
276         catch (Exception e) {
277             throw processException(e);
278         }
279         finally {
280             closeSession(session);
281         }
282 
283         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
284 
285         EntityCacheUtil.putResult(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
286             RatingsStatsImpl.class, ratingsStats.getPrimaryKey(), ratingsStats);
287 
288         if (!isNew &&
289                 ((ratingsStats.getClassNameId() != ratingsStatsModelImpl.getOriginalClassNameId()) ||
290                 (ratingsStats.getClassPK() != ratingsStatsModelImpl.getOriginalClassPK()))) {
291             FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_C_C,
292                 new Object[] {
293                     new Long(ratingsStatsModelImpl.getOriginalClassNameId()),
294                     new Long(ratingsStatsModelImpl.getOriginalClassPK())
295                 });
296         }
297 
298         if (isNew ||
299                 ((ratingsStats.getClassNameId() != ratingsStatsModelImpl.getOriginalClassNameId()) ||
300                 (ratingsStats.getClassPK() != ratingsStatsModelImpl.getOriginalClassPK()))) {
301             FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_C,
302                 new Object[] {
303                     new Long(ratingsStats.getClassNameId()),
304                     new Long(ratingsStats.getClassPK())
305                 }, ratingsStats);
306         }
307 
308         return ratingsStats;
309     }
310 
311     public RatingsStats findByPrimaryKey(long statsId)
312         throws NoSuchStatsException, SystemException {
313         RatingsStats ratingsStats = fetchByPrimaryKey(statsId);
314 
315         if (ratingsStats == null) {
316             if (_log.isWarnEnabled()) {
317                 _log.warn("No RatingsStats exists with the primary key " +
318                     statsId);
319             }
320 
321             throw new NoSuchStatsException(
322                 "No RatingsStats exists with the primary key " + statsId);
323         }
324 
325         return ratingsStats;
326     }
327 
328     public RatingsStats fetchByPrimaryKey(long statsId)
329         throws SystemException {
330         RatingsStats ratingsStats = (RatingsStats)EntityCacheUtil.getResult(RatingsStatsModelImpl.ENTITY_CACHE_ENABLED,
331                 RatingsStatsImpl.class, statsId, this);
332 
333         if (ratingsStats == null) {
334             Session session = null;
335 
336             try {
337                 session = openSession();
338 
339                 ratingsStats = (RatingsStats)session.get(RatingsStatsImpl.class,
340                         new Long(statsId));
341             }
342             catch (Exception e) {
343                 throw processException(e);
344             }
345             finally {
346                 if (ratingsStats != null) {
347                     cacheResult(ratingsStats);
348                 }
349 
350                 closeSession(session);
351             }
352         }
353 
354         return ratingsStats;
355     }
356 
357     public RatingsStats findByC_C(long classNameId, long classPK)
358         throws NoSuchStatsException, SystemException {
359         RatingsStats ratingsStats = fetchByC_C(classNameId, classPK);
360 
361         if (ratingsStats == null) {
362             StringBuilder msg = new StringBuilder();
363 
364             msg.append("No RatingsStats exists with the key {");
365 
366             msg.append("classNameId=" + classNameId);
367 
368             msg.append(", ");
369             msg.append("classPK=" + classPK);
370 
371             msg.append(StringPool.CLOSE_CURLY_BRACE);
372 
373             if (_log.isWarnEnabled()) {
374                 _log.warn(msg.toString());
375             }
376 
377             throw new NoSuchStatsException(msg.toString());
378         }
379 
380         return ratingsStats;
381     }
382 
383     public RatingsStats fetchByC_C(long classNameId, long classPK)
384         throws SystemException {
385         return fetchByC_C(classNameId, classPK, true);
386     }
387 
388     public RatingsStats fetchByC_C(long classNameId, long classPK,
389         boolean retrieveFromCache) throws SystemException {
390         Object[] finderArgs = new Object[] {
391                 new Long(classNameId), new Long(classPK)
392             };
393 
394         Object result = null;
395 
396         if (retrieveFromCache) {
397             result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_C_C,
398                     finderArgs, this);
399         }
400 
401         if (result == null) {
402             Session session = null;
403 
404             try {
405                 session = openSession();
406 
407                 StringBuilder query = new StringBuilder();
408 
409                 query.append(
410                     "FROM com.liferay.portlet.ratings.model.RatingsStats WHERE ");
411 
412                 query.append("classNameId = ?");
413 
414                 query.append(" AND ");
415 
416                 query.append("classPK = ?");
417 
418                 query.append(" ");
419 
420                 Query q = session.createQuery(query.toString());
421 
422                 QueryPos qPos = QueryPos.getInstance(q);
423 
424                 qPos.add(classNameId);
425 
426                 qPos.add(classPK);
427 
428                 List<RatingsStats> list = q.list();
429 
430                 result = list;
431 
432                 RatingsStats ratingsStats = null;
433 
434                 if (list.isEmpty()) {
435                     FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_C,
436                         finderArgs, list);
437                 }
438                 else {
439                     ratingsStats = list.get(0);
440 
441                     cacheResult(ratingsStats);
442 
443                     if ((ratingsStats.getClassNameId() != classNameId) ||
444                             (ratingsStats.getClassPK() != classPK)) {
445                         FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_C,
446                             finderArgs, list);
447                     }
448                 }
449 
450                 return ratingsStats;
451             }
452             catch (Exception e) {
453                 throw processException(e);
454             }
455             finally {
456                 if (result == null) {
457                     FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_C,
458                         finderArgs, new ArrayList<RatingsStats>());
459                 }
460 
461                 closeSession(session);
462             }
463         }
464         else {
465             if (result instanceof List) {
466                 return null;
467             }
468             else {
469                 return (RatingsStats)result;
470             }
471         }
472     }
473 
474     public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery)
475         throws SystemException {
476         Session session = null;
477 
478         try {
479             session = openSession();
480 
481             dynamicQuery.compile(session);
482 
483             return dynamicQuery.list();
484         }
485         catch (Exception e) {
486             throw processException(e);
487         }
488         finally {
489             closeSession(session);
490         }
491     }
492 
493     public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery,
494         int start, int end) throws SystemException {
495         Session session = null;
496 
497         try {
498             session = openSession();
499 
500             dynamicQuery.setLimit(start, end);
501 
502             dynamicQuery.compile(session);
503 
504             return dynamicQuery.list();
505         }
506         catch (Exception e) {
507             throw processException(e);
508         }
509         finally {
510             closeSession(session);
511         }
512     }
513 
514     public List<RatingsStats> findAll() throws SystemException {
515         return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
516     }
517 
518     public List<RatingsStats> findAll(int start, int end)
519         throws SystemException {
520         return findAll(start, end, null);
521     }
522 
523     public List<RatingsStats> findAll(int start, int end, OrderByComparator obc)
524         throws SystemException {
525         Object[] finderArgs = new Object[] {
526                 String.valueOf(start), String.valueOf(end), String.valueOf(obc)
527             };
528 
529         List<RatingsStats> list = (List<RatingsStats>)FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
530                 finderArgs, this);
531 
532         if (list == null) {
533             Session session = null;
534 
535             try {
536                 session = openSession();
537 
538                 StringBuilder query = new StringBuilder();
539 
540                 query.append(
541                     "FROM com.liferay.portlet.ratings.model.RatingsStats ");
542 
543                 if (obc != null) {
544                     query.append("ORDER BY ");
545                     query.append(obc.getOrderBy());
546                 }
547 
548                 Query q = session.createQuery(query.toString());
549 
550                 if (obc == null) {
551                     list = (List<RatingsStats>)QueryUtil.list(q, getDialect(),
552                             start, end, false);
553 
554                     Collections.sort(list);
555                 }
556                 else {
557                     list = (List<RatingsStats>)QueryUtil.list(q, getDialect(),
558                             start, end);
559                 }
560             }
561             catch (Exception e) {
562                 throw processException(e);
563             }
564             finally {
565                 if (list == null) {
566                     list = new ArrayList<RatingsStats>();
567                 }
568 
569                 cacheResult(list);
570 
571                 FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs, list);
572 
573                 closeSession(session);
574             }
575         }
576 
577         return list;
578     }
579 
580     public void removeByC_C(long classNameId, long classPK)
581         throws NoSuchStatsException, SystemException {
582         RatingsStats ratingsStats = findByC_C(classNameId, classPK);
583 
584         remove(ratingsStats);
585     }
586 
587     public void removeAll() throws SystemException {
588         for (RatingsStats ratingsStats : findAll()) {
589             remove(ratingsStats);
590         }
591     }
592 
593     public int countByC_C(long classNameId, long classPK)
594         throws SystemException {
595         Object[] finderArgs = new Object[] {
596                 new Long(classNameId), new Long(classPK)
597             };
598 
599         Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_C_C,
600                 finderArgs, this);
601 
602         if (count == null) {
603             Session session = null;
604 
605             try {
606                 session = openSession();
607 
608                 StringBuilder query = new StringBuilder();
609 
610                 query.append("SELECT COUNT(*) ");
611                 query.append(
612                     "FROM com.liferay.portlet.ratings.model.RatingsStats WHERE ");
613 
614                 query.append("classNameId = ?");
615 
616                 query.append(" AND ");
617 
618                 query.append("classPK = ?");
619 
620                 query.append(" ");
621 
622                 Query q = session.createQuery(query.toString());
623 
624                 QueryPos qPos = QueryPos.getInstance(q);
625 
626                 qPos.add(classNameId);
627 
628                 qPos.add(classPK);
629 
630                 count = (Long)q.uniqueResult();
631             }
632             catch (Exception e) {
633                 throw processException(e);
634             }
635             finally {
636                 if (count == null) {
637                     count = Long.valueOf(0);
638                 }
639 
640                 FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_C_C, finderArgs,
641                     count);
642 
643                 closeSession(session);
644             }
645         }
646 
647         return count.intValue();
648     }
649 
650     public int countAll() throws SystemException {
651         Object[] finderArgs = new Object[0];
652 
653         Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
654                 finderArgs, this);
655 
656         if (count == null) {
657             Session session = null;
658 
659             try {
660                 session = openSession();
661 
662                 Query q = session.createQuery(
663                         "SELECT COUNT(*) FROM com.liferay.portlet.ratings.model.RatingsStats");
664 
665                 count = (Long)q.uniqueResult();
666             }
667             catch (Exception e) {
668                 throw processException(e);
669             }
670             finally {
671                 if (count == null) {
672                     count = Long.valueOf(0);
673                 }
674 
675                 FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
676                     count);
677 
678                 closeSession(session);
679             }
680         }
681 
682         return count.intValue();
683     }
684 
685     public void afterPropertiesSet() {
686         String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
687                     com.liferay.portal.util.PropsUtil.get(
688                         "value.object.listener.com.liferay.portlet.ratings.model.RatingsStats")));
689 
690         if (listenerClassNames.length > 0) {
691             try {
692                 List<ModelListener<RatingsStats>> listenersList = new ArrayList<ModelListener<RatingsStats>>();
693 
694                 for (String listenerClassName : listenerClassNames) {
695                     listenersList.add((ModelListener<RatingsStats>)Class.forName(
696                             listenerClassName).newInstance());
697                 }
698 
699                 listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
700             }
701             catch (Exception e) {
702                 _log.error(e);
703             }
704         }
705     }
706 
707     @BeanReference(name = "com.liferay.portlet.ratings.service.persistence.RatingsEntryPersistence.impl")
708     protected com.liferay.portlet.ratings.service.persistence.RatingsEntryPersistence ratingsEntryPersistence;
709     @BeanReference(name = "com.liferay.portlet.ratings.service.persistence.RatingsStatsPersistence.impl")
710     protected com.liferay.portlet.ratings.service.persistence.RatingsStatsPersistence ratingsStatsPersistence;
711     private static Log _log = LogFactoryUtil.getLog(RatingsStatsPersistenceImpl.class);
712 }