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.portal.service.persistence;
24  
25  import com.liferay.portal.NoSuchAccountException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.dao.DynamicQuery;
28  import com.liferay.portal.kernel.dao.DynamicQueryInitializer;
29  import com.liferay.portal.kernel.util.GetterUtil;
30  import com.liferay.portal.kernel.util.OrderByComparator;
31  import com.liferay.portal.kernel.util.StringMaker;
32  import com.liferay.portal.kernel.util.StringUtil;
33  import com.liferay.portal.model.Account;
34  import com.liferay.portal.model.ModelListener;
35  import com.liferay.portal.model.impl.AccountImpl;
36  import com.liferay.portal.model.impl.AccountModelImpl;
37  import com.liferay.portal.spring.hibernate.FinderCache;
38  import com.liferay.portal.spring.hibernate.HibernateUtil;
39  import com.liferay.portal.util.PropsUtil;
40  
41  import com.liferay.util.dao.hibernate.QueryUtil;
42  
43  import org.apache.commons.logging.Log;
44  import org.apache.commons.logging.LogFactory;
45  
46  import org.hibernate.Query;
47  import org.hibernate.Session;
48  
49  import java.util.ArrayList;
50  import java.util.Collections;
51  import java.util.Iterator;
52  import java.util.List;
53  
54  /**
55   * <a href="AccountPersistenceImpl.java.html"><b><i>View Source</i></b></a>
56   *
57   * @author Brian Wing Shun Chan
58   *
59   */
60  public class AccountPersistenceImpl extends BasePersistence
61      implements AccountPersistence {
62      public Account create(long accountId) {
63          Account account = new AccountImpl();
64  
65          account.setNew(true);
66          account.setPrimaryKey(accountId);
67  
68          return account;
69      }
70  
71      public Account remove(long accountId)
72          throws NoSuchAccountException, SystemException {
73          Session session = null;
74  
75          try {
76              session = openSession();
77  
78              Account account = (Account)session.get(AccountImpl.class,
79                      new Long(accountId));
80  
81              if (account == null) {
82                  if (_log.isWarnEnabled()) {
83                      _log.warn("No Account exists with the primary key " +
84                          accountId);
85                  }
86  
87                  throw new NoSuchAccountException(
88                      "No Account exists with the primary key " + accountId);
89              }
90  
91              return remove(account);
92          }
93          catch (NoSuchAccountException nsee) {
94              throw nsee;
95          }
96          catch (Exception e) {
97              throw HibernateUtil.processException(e);
98          }
99          finally {
100             closeSession(session);
101         }
102     }
103 
104     public Account remove(Account account) throws SystemException {
105         if (_listeners != null) {
106             for (ModelListener listener : _listeners) {
107                 listener.onBeforeRemove(account);
108             }
109         }
110 
111         account = removeImpl(account);
112 
113         if (_listeners != null) {
114             for (ModelListener listener : _listeners) {
115                 listener.onAfterRemove(account);
116             }
117         }
118 
119         return account;
120     }
121 
122     protected Account removeImpl(Account account) throws SystemException {
123         Session session = null;
124 
125         try {
126             session = openSession();
127 
128             session.delete(account);
129 
130             session.flush();
131 
132             return account;
133         }
134         catch (Exception e) {
135             throw HibernateUtil.processException(e);
136         }
137         finally {
138             closeSession(session);
139 
140             FinderCache.clearCache(Account.class.getName());
141         }
142     }
143 
144     /**
145      * @deprecated Use <code>update(Account account, boolean merge)</code>.
146      */
147     public Account update(Account account) throws SystemException {
148         if (_log.isWarnEnabled()) {
149             _log.warn(
150                 "Using the deprecated update(Account account) method. Use update(Account account, boolean merge) instead.");
151         }
152 
153         return update(account, false);
154     }
155 
156     /**
157      * Add, update, or merge, the entity. This method also calls the model
158      * listeners to trigger the proper events associated with adding, deleting,
159      * or updating an entity.
160      *
161      * @param        account the entity to add, update, or merge
162      * @param        merge boolean value for whether to merge the entity. The
163      *                default value is false. Setting merge to true is more
164      *                expensive and should only be true when account is
165      *                transient. See LEP-5473 for a detailed discussion of this
166      *                method.
167      * @return        true if the portlet can be displayed via Ajax
168      */
169     public Account update(Account account, boolean merge)
170         throws SystemException {
171         boolean isNew = account.isNew();
172 
173         if (_listeners != null) {
174             for (ModelListener listener : _listeners) {
175                 if (isNew) {
176                     listener.onBeforeCreate(account);
177                 }
178                 else {
179                     listener.onBeforeUpdate(account);
180                 }
181             }
182         }
183 
184         account = updateImpl(account, merge);
185 
186         if (_listeners != null) {
187             for (ModelListener listener : _listeners) {
188                 if (isNew) {
189                     listener.onAfterCreate(account);
190                 }
191                 else {
192                     listener.onAfterUpdate(account);
193                 }
194             }
195         }
196 
197         return account;
198     }
199 
200     public Account updateImpl(com.liferay.portal.model.Account account,
201         boolean merge) throws SystemException {
202         Session session = null;
203 
204         try {
205             session = openSession();
206 
207             if (merge) {
208                 session.merge(account);
209             }
210             else {
211                 if (account.isNew()) {
212                     session.save(account);
213                 }
214             }
215 
216             session.flush();
217 
218             account.setNew(false);
219 
220             return account;
221         }
222         catch (Exception e) {
223             throw HibernateUtil.processException(e);
224         }
225         finally {
226             closeSession(session);
227 
228             FinderCache.clearCache(Account.class.getName());
229         }
230     }
231 
232     public Account findByPrimaryKey(long accountId)
233         throws NoSuchAccountException, SystemException {
234         Account account = fetchByPrimaryKey(accountId);
235 
236         if (account == null) {
237             if (_log.isWarnEnabled()) {
238                 _log.warn("No Account exists with the primary key " +
239                     accountId);
240             }
241 
242             throw new NoSuchAccountException(
243                 "No Account exists with the primary key " + accountId);
244         }
245 
246         return account;
247     }
248 
249     public Account fetchByPrimaryKey(long accountId) throws SystemException {
250         Session session = null;
251 
252         try {
253             session = openSession();
254 
255             return (Account)session.get(AccountImpl.class, new Long(accountId));
256         }
257         catch (Exception e) {
258             throw HibernateUtil.processException(e);
259         }
260         finally {
261             closeSession(session);
262         }
263     }
264 
265     public List<Account> findWithDynamicQuery(
266         DynamicQueryInitializer queryInitializer) throws SystemException {
267         Session session = null;
268 
269         try {
270             session = openSession();
271 
272             DynamicQuery query = queryInitializer.initialize(session);
273 
274             return query.list();
275         }
276         catch (Exception e) {
277             throw HibernateUtil.processException(e);
278         }
279         finally {
280             closeSession(session);
281         }
282     }
283 
284     public List<Account> findWithDynamicQuery(
285         DynamicQueryInitializer queryInitializer, int begin, int end)
286         throws SystemException {
287         Session session = null;
288 
289         try {
290             session = openSession();
291 
292             DynamicQuery query = queryInitializer.initialize(session);
293 
294             query.setLimit(begin, end);
295 
296             return query.list();
297         }
298         catch (Exception e) {
299             throw HibernateUtil.processException(e);
300         }
301         finally {
302             closeSession(session);
303         }
304     }
305 
306     public List<Account> findAll() throws SystemException {
307         return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
308     }
309 
310     public List<Account> findAll(int begin, int end) throws SystemException {
311         return findAll(begin, end, null);
312     }
313 
314     public List<Account> findAll(int begin, int end, OrderByComparator obc)
315         throws SystemException {
316         boolean finderClassNameCacheEnabled = AccountModelImpl.CACHE_ENABLED;
317         String finderClassName = Account.class.getName();
318         String finderMethodName = "findAll";
319         String[] finderParams = new String[] {
320                 "java.lang.Integer", "java.lang.Integer",
321                 "com.liferay.portal.kernel.util.OrderByComparator"
322             };
323         Object[] finderArgs = new Object[] {
324                 String.valueOf(begin), String.valueOf(end), String.valueOf(obc)
325             };
326 
327         Object result = null;
328 
329         if (finderClassNameCacheEnabled) {
330             result = FinderCache.getResult(finderClassName, finderMethodName,
331                     finderParams, finderArgs, getSessionFactory());
332         }
333 
334         if (result == null) {
335             Session session = null;
336 
337             try {
338                 session = openSession();
339 
340                 StringMaker query = new StringMaker();
341 
342                 query.append("FROM com.liferay.portal.model.Account ");
343 
344                 if (obc != null) {
345                     query.append("ORDER BY ");
346                     query.append(obc.getOrderBy());
347                 }
348 
349                 Query q = session.createQuery(query.toString());
350 
351                 List<Account> list = (List<Account>)QueryUtil.list(q,
352                         getDialect(), begin, end);
353 
354                 if (obc == null) {
355                     Collections.sort(list);
356                 }
357 
358                 FinderCache.putResult(finderClassNameCacheEnabled,
359                     finderClassName, finderMethodName, finderParams,
360                     finderArgs, list);
361 
362                 return list;
363             }
364             catch (Exception e) {
365                 throw HibernateUtil.processException(e);
366             }
367             finally {
368                 closeSession(session);
369             }
370         }
371         else {
372             return (List<Account>)result;
373         }
374     }
375 
376     public void removeAll() throws SystemException {
377         for (Account account : findAll()) {
378             remove(account);
379         }
380     }
381 
382     public int countAll() throws SystemException {
383         boolean finderClassNameCacheEnabled = AccountModelImpl.CACHE_ENABLED;
384         String finderClassName = Account.class.getName();
385         String finderMethodName = "countAll";
386         String[] finderParams = new String[] {  };
387         Object[] finderArgs = new Object[] {  };
388 
389         Object result = null;
390 
391         if (finderClassNameCacheEnabled) {
392             result = FinderCache.getResult(finderClassName, finderMethodName,
393                     finderParams, finderArgs, getSessionFactory());
394         }
395 
396         if (result == null) {
397             Session session = null;
398 
399             try {
400                 session = openSession();
401 
402                 Query q = session.createQuery(
403                         "SELECT COUNT(*) FROM com.liferay.portal.model.Account");
404 
405                 Long count = null;
406 
407                 Iterator<Long> itr = q.list().iterator();
408 
409                 if (itr.hasNext()) {
410                     count = itr.next();
411                 }
412 
413                 if (count == null) {
414                     count = new Long(0);
415                 }
416 
417                 FinderCache.putResult(finderClassNameCacheEnabled,
418                     finderClassName, finderMethodName, finderParams,
419                     finderArgs, count);
420 
421                 return count.intValue();
422             }
423             catch (Exception e) {
424                 throw HibernateUtil.processException(e);
425             }
426             finally {
427                 closeSession(session);
428             }
429         }
430         else {
431             return ((Long)result).intValue();
432         }
433     }
434 
435     protected void initDao() {
436         String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
437                     PropsUtil.get(
438                         "value.object.listener.com.liferay.portal.model.Account")));
439 
440         if (listenerClassNames.length > 0) {
441             try {
442                 List<ModelListener> listeners = new ArrayList<ModelListener>();
443 
444                 for (String listenerClassName : listenerClassNames) {
445                     listeners.add((ModelListener)Class.forName(
446                             listenerClassName).newInstance());
447                 }
448 
449                 _listeners = listeners.toArray(new ModelListener[listeners.size()]);
450             }
451             catch (Exception e) {
452                 _log.error(e);
453             }
454         }
455     }
456 
457     private static Log _log = LogFactory.getLog(AccountPersistenceImpl.class);
458     private ModelListener[] _listeners;
459 }