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