1   /**
2    * Copyright (c) 2000-2009 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.NoSuchOrganizationException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.annotation.BeanReference;
28  import com.liferay.portal.kernel.cache.CacheRegistry;
29  import com.liferay.portal.kernel.dao.jdbc.MappingSqlQuery;
30  import com.liferay.portal.kernel.dao.jdbc.MappingSqlQueryFactoryUtil;
31  import com.liferay.portal.kernel.dao.jdbc.RowMapper;
32  import com.liferay.portal.kernel.dao.jdbc.SqlUpdate;
33  import com.liferay.portal.kernel.dao.jdbc.SqlUpdateFactoryUtil;
34  import com.liferay.portal.kernel.dao.orm.DynamicQuery;
35  import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
36  import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
37  import com.liferay.portal.kernel.dao.orm.FinderPath;
38  import com.liferay.portal.kernel.dao.orm.Query;
39  import com.liferay.portal.kernel.dao.orm.QueryPos;
40  import com.liferay.portal.kernel.dao.orm.QueryUtil;
41  import com.liferay.portal.kernel.dao.orm.SQLQuery;
42  import com.liferay.portal.kernel.dao.orm.Session;
43  import com.liferay.portal.kernel.dao.orm.Type;
44  import com.liferay.portal.kernel.log.Log;
45  import com.liferay.portal.kernel.log.LogFactoryUtil;
46  import com.liferay.portal.kernel.util.GetterUtil;
47  import com.liferay.portal.kernel.util.OrderByComparator;
48  import com.liferay.portal.kernel.util.StringPool;
49  import com.liferay.portal.kernel.util.StringUtil;
50  import com.liferay.portal.kernel.util.Validator;
51  import com.liferay.portal.model.ModelListener;
52  import com.liferay.portal.model.Organization;
53  import com.liferay.portal.model.impl.OrganizationImpl;
54  import com.liferay.portal.model.impl.OrganizationModelImpl;
55  import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
56  
57  import java.sql.Types;
58  
59  import java.util.ArrayList;
60  import java.util.Collections;
61  import java.util.List;
62  
63  /**
64   * <a href="OrganizationPersistenceImpl.java.html"><b><i>View Source</i></b></a>
65   *
66   * @author Brian Wing Shun Chan
67   *
68   */
69  public class OrganizationPersistenceImpl extends BasePersistenceImpl
70      implements OrganizationPersistence {
71      public static final String FINDER_CLASS_NAME_ENTITY = OrganizationImpl.class.getName();
72      public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
73          ".List";
74      public static final FinderPath FINDER_PATH_FIND_BY_COMPANYID = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
75              OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
76              "findByCompanyId", new String[] { Long.class.getName() });
77      public static final FinderPath FINDER_PATH_FIND_BY_OBC_COMPANYID = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
78              OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
79              "findByCompanyId",
80              new String[] {
81                  Long.class.getName(),
82                  
83              "java.lang.Integer", "java.lang.Integer",
84                  "com.liferay.portal.kernel.util.OrderByComparator"
85              });
86      public static final FinderPath FINDER_PATH_COUNT_BY_COMPANYID = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
87              OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
88              "countByCompanyId", new String[] { Long.class.getName() });
89      public static final FinderPath FINDER_PATH_FIND_BY_LOCATIONS = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
90              OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
91              "findByLocations", new String[] { Long.class.getName() });
92      public static final FinderPath FINDER_PATH_FIND_BY_OBC_LOCATIONS = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
93              OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
94              "findByLocations",
95              new String[] {
96                  Long.class.getName(),
97                  
98              "java.lang.Integer", "java.lang.Integer",
99                  "com.liferay.portal.kernel.util.OrderByComparator"
100             });
101     public static final FinderPath FINDER_PATH_COUNT_BY_LOCATIONS = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
102             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
103             "countByLocations", new String[] { Long.class.getName() });
104     public static final FinderPath FINDER_PATH_FIND_BY_C_P = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
105             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
106             "findByC_P",
107             new String[] { Long.class.getName(), Long.class.getName() });
108     public static final FinderPath FINDER_PATH_FIND_BY_OBC_C_P = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
109             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
110             "findByC_P",
111             new String[] {
112                 Long.class.getName(), Long.class.getName(),
113                 
114             "java.lang.Integer", "java.lang.Integer",
115                 "com.liferay.portal.kernel.util.OrderByComparator"
116             });
117     public static final FinderPath FINDER_PATH_COUNT_BY_C_P = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
118             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
119             "countByC_P",
120             new String[] { Long.class.getName(), Long.class.getName() });
121     public static final FinderPath FINDER_PATH_FETCH_BY_C_N = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
122             OrganizationModelImpl.FINDER_CACHE_ENABLED,
123             FINDER_CLASS_NAME_ENTITY, "fetchByC_N",
124             new String[] { Long.class.getName(), String.class.getName() });
125     public static final FinderPath FINDER_PATH_COUNT_BY_C_N = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
126             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
127             "countByC_N",
128             new String[] { Long.class.getName(), String.class.getName() });
129     public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
130             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
131             "findAll", new String[0]);
132     public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
133             OrganizationModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
134             "countAll", new String[0]);
135 
136     public void cacheResult(Organization organization) {
137         EntityCacheUtil.putResult(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
138             OrganizationImpl.class, organization.getPrimaryKey(), organization);
139 
140         FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_N,
141             new Object[] {
142                 new Long(organization.getCompanyId()),
143                 
144             organization.getName()
145             }, organization);
146     }
147 
148     public void cacheResult(List<Organization> organizations) {
149         for (Organization organization : organizations) {
150             if (EntityCacheUtil.getResult(
151                         OrganizationModelImpl.ENTITY_CACHE_ENABLED,
152                         OrganizationImpl.class, organization.getPrimaryKey(),
153                         this) == null) {
154                 cacheResult(organization);
155             }
156         }
157     }
158 
159     public void clearCache() {
160         CacheRegistry.clear(OrganizationImpl.class.getName());
161         EntityCacheUtil.clearCache(OrganizationImpl.class.getName());
162         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
163         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
164     }
165 
166     public Organization create(long organizationId) {
167         Organization organization = new OrganizationImpl();
168 
169         organization.setNew(true);
170         organization.setPrimaryKey(organizationId);
171 
172         return organization;
173     }
174 
175     public Organization remove(long organizationId)
176         throws NoSuchOrganizationException, SystemException {
177         Session session = null;
178 
179         try {
180             session = openSession();
181 
182             Organization organization = (Organization)session.get(OrganizationImpl.class,
183                     new Long(organizationId));
184 
185             if (organization == null) {
186                 if (_log.isWarnEnabled()) {
187                     _log.warn("No Organization exists with the primary key " +
188                         organizationId);
189                 }
190 
191                 throw new NoSuchOrganizationException(
192                     "No Organization exists with the primary key " +
193                     organizationId);
194             }
195 
196             return remove(organization);
197         }
198         catch (NoSuchOrganizationException nsee) {
199             throw nsee;
200         }
201         catch (Exception e) {
202             throw processException(e);
203         }
204         finally {
205             closeSession(session);
206         }
207     }
208 
209     public Organization remove(Organization organization)
210         throws SystemException {
211         for (ModelListener<Organization> listener : listeners) {
212             listener.onBeforeRemove(organization);
213         }
214 
215         organization = removeImpl(organization);
216 
217         for (ModelListener<Organization> listener : listeners) {
218             listener.onAfterRemove(organization);
219         }
220 
221         return organization;
222     }
223 
224     protected Organization removeImpl(Organization organization)
225         throws SystemException {
226         try {
227             clearGroups.clear(organization.getPrimaryKey());
228         }
229         catch (Exception e) {
230             throw processException(e);
231         }
232         finally {
233             FinderCacheUtil.clearCache("Groups_Orgs");
234         }
235 
236         try {
237             clearUsers.clear(organization.getPrimaryKey());
238         }
239         catch (Exception e) {
240             throw processException(e);
241         }
242         finally {
243             FinderCacheUtil.clearCache("Users_Orgs");
244         }
245 
246         shrinkTree(organization);
247 
248         Session session = null;
249 
250         try {
251             session = openSession();
252 
253             if (organization.isCachedModel() || BatchSessionUtil.isEnabled()) {
254                 Object staleObject = session.get(OrganizationImpl.class,
255                         organization.getPrimaryKeyObj());
256 
257                 if (staleObject != null) {
258                     session.evict(staleObject);
259                 }
260             }
261 
262             session.delete(organization);
263 
264             session.flush();
265         }
266         catch (Exception e) {
267             throw processException(e);
268         }
269         finally {
270             closeSession(session);
271         }
272 
273         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
274 
275         OrganizationModelImpl organizationModelImpl = (OrganizationModelImpl)organization;
276 
277         FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_C_N,
278             new Object[] {
279                 new Long(organizationModelImpl.getOriginalCompanyId()),
280                 
281             organizationModelImpl.getOriginalName()
282             });
283 
284         EntityCacheUtil.removeResult(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
285             OrganizationImpl.class, organization.getPrimaryKey());
286 
287         return organization;
288     }
289 
290     /**
291      * @deprecated Use <code>update(Organization organization, boolean merge)</code>.
292      */
293     public Organization update(Organization organization)
294         throws SystemException {
295         if (_log.isWarnEnabled()) {
296             _log.warn(
297                 "Using the deprecated update(Organization organization) method. Use update(Organization organization, boolean merge) instead.");
298         }
299 
300         return update(organization, false);
301     }
302 
303     /**
304      * Add, update, or merge, the entity. This method also calls the model
305      * listeners to trigger the proper events associated with adding, deleting,
306      * or updating an entity.
307      *
308      * @param        organization the entity to add, update, or merge
309      * @param        merge boolean value for whether to merge the entity. The
310      *                default value is false. Setting merge to true is more
311      *                expensive and should only be true when organization is
312      *                transient. See LEP-5473 for a detailed discussion of this
313      *                method.
314      * @return        true if the portlet can be displayed via Ajax
315      */
316     public Organization update(Organization organization, boolean merge)
317         throws SystemException {
318         boolean isNew = organization.isNew();
319 
320         for (ModelListener<Organization> listener : listeners) {
321             if (isNew) {
322                 listener.onBeforeCreate(organization);
323             }
324             else {
325                 listener.onBeforeUpdate(organization);
326             }
327         }
328 
329         organization = updateImpl(organization, merge);
330 
331         for (ModelListener<Organization> listener : listeners) {
332             if (isNew) {
333                 listener.onAfterCreate(organization);
334             }
335             else {
336                 listener.onAfterUpdate(organization);
337             }
338         }
339 
340         return organization;
341     }
342 
343     public Organization updateImpl(
344         com.liferay.portal.model.Organization organization, boolean merge)
345         throws SystemException {
346         boolean isNew = organization.isNew();
347 
348         OrganizationModelImpl organizationModelImpl = (OrganizationModelImpl)organization;
349 
350         if (isNew) {
351             expandTree(organization);
352         }
353         else {
354             if (organization.getParentOrganizationId() != organizationModelImpl.getOriginalParentOrganizationId()) {
355                 shrinkTree(organization);
356                 expandTree(organization);
357             }
358         }
359 
360         Session session = null;
361 
362         try {
363             session = openSession();
364 
365             BatchSessionUtil.update(session, organization, merge);
366 
367             organization.setNew(false);
368         }
369         catch (Exception e) {
370             throw processException(e);
371         }
372         finally {
373             closeSession(session);
374         }
375 
376         FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
377 
378         EntityCacheUtil.putResult(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
379             OrganizationImpl.class, organization.getPrimaryKey(), organization);
380 
381         if (!isNew &&
382                 ((organization.getCompanyId() != organizationModelImpl.getOriginalCompanyId()) ||
383                 !Validator.equals(organization.getName(),
384                     organizationModelImpl.getOriginalName()))) {
385             FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_C_N,
386                 new Object[] {
387                     new Long(organizationModelImpl.getOriginalCompanyId()),
388                     
389                 organizationModelImpl.getOriginalName()
390                 });
391         }
392 
393         if (isNew ||
394                 ((organization.getCompanyId() != organizationModelImpl.getOriginalCompanyId()) ||
395                 !Validator.equals(organization.getName(),
396                     organizationModelImpl.getOriginalName()))) {
397             FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_N,
398                 new Object[] {
399                     new Long(organization.getCompanyId()),
400                     
401                 organization.getName()
402                 }, organization);
403         }
404 
405         return organization;
406     }
407 
408     public Organization findByPrimaryKey(long organizationId)
409         throws NoSuchOrganizationException, SystemException {
410         Organization organization = fetchByPrimaryKey(organizationId);
411 
412         if (organization == null) {
413             if (_log.isWarnEnabled()) {
414                 _log.warn("No Organization exists with the primary key " +
415                     organizationId);
416             }
417 
418             throw new NoSuchOrganizationException(
419                 "No Organization exists with the primary key " +
420                 organizationId);
421         }
422 
423         return organization;
424     }
425 
426     public Organization fetchByPrimaryKey(long organizationId)
427         throws SystemException {
428         Organization organization = (Organization)EntityCacheUtil.getResult(OrganizationModelImpl.ENTITY_CACHE_ENABLED,
429                 OrganizationImpl.class, organizationId, this);
430 
431         if (organization == null) {
432             Session session = null;
433 
434             try {
435                 session = openSession();
436 
437                 organization = (Organization)session.get(OrganizationImpl.class,
438                         new Long(organizationId));
439             }
440             catch (Exception e) {
441                 throw processException(e);
442             }
443             finally {
444                 if (organization != null) {
445                     cacheResult(organization);
446                 }
447 
448                 closeSession(session);
449             }
450         }
451 
452         return organization;
453     }
454 
455     public List<Organization> findByCompanyId(long companyId)
456         throws SystemException {
457         Object[] finderArgs = new Object[] { new Long(companyId) };
458 
459         List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_COMPANYID,
460                 finderArgs, this);
461 
462         if (list == null) {
463             Session session = null;
464 
465             try {
466                 session = openSession();
467 
468                 StringBuilder query = new StringBuilder();
469 
470                 query.append(
471                     "SELECT organization FROM Organization organization WHERE ");
472 
473                 query.append("organization.companyId = ?");
474 
475                 query.append(" ");
476 
477                 query.append("ORDER BY ");
478 
479                 query.append("organization.name ASC");
480 
481                 Query q = session.createQuery(query.toString());
482 
483                 QueryPos qPos = QueryPos.getInstance(q);
484 
485                 qPos.add(companyId);
486 
487                 list = q.list();
488             }
489             catch (Exception e) {
490                 throw processException(e);
491             }
492             finally {
493                 if (list == null) {
494                     list = new ArrayList<Organization>();
495                 }
496 
497                 cacheResult(list);
498 
499                 FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_COMPANYID,
500                     finderArgs, list);
501 
502                 closeSession(session);
503             }
504         }
505 
506         return list;
507     }
508 
509     public List<Organization> findByCompanyId(long companyId, int start, int end)
510         throws SystemException {
511         return findByCompanyId(companyId, start, end, null);
512     }
513 
514     public List<Organization> findByCompanyId(long companyId, int start,
515         int end, OrderByComparator obc) throws SystemException {
516         Object[] finderArgs = new Object[] {
517                 new Long(companyId),
518                 
519                 String.valueOf(start), String.valueOf(end), String.valueOf(obc)
520             };
521 
522         List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_OBC_COMPANYID,
523                 finderArgs, this);
524 
525         if (list == null) {
526             Session session = null;
527 
528             try {
529                 session = openSession();
530 
531                 StringBuilder query = new StringBuilder();
532 
533                 query.append(
534                     "SELECT organization FROM Organization organization WHERE ");
535 
536                 query.append("organization.companyId = ?");
537 
538                 query.append(" ");
539 
540                 if (obc != null) {
541                     query.append("ORDER BY ");
542 
543                     String[] orderByFields = obc.getOrderByFields();
544 
545                     for (int i = 0; i < orderByFields.length; i++) {
546                         query.append("organization.");
547                         query.append(orderByFields[i]);
548 
549                         if (obc.isAscending()) {
550                             query.append(" ASC");
551                         }
552                         else {
553                             query.append(" DESC");
554                         }
555 
556                         if ((i + 1) < orderByFields.length) {
557                             query.append(", ");
558                         }
559                     }
560                 }
561 
562                 else {
563                     query.append("ORDER BY ");
564 
565                     query.append("organization.name ASC");
566                 }
567 
568                 Query q = session.createQuery(query.toString());
569 
570                 QueryPos qPos = QueryPos.getInstance(q);
571 
572                 qPos.add(companyId);
573 
574                 list = (List<Organization>)QueryUtil.list(q, getDialect(),
575                         start, end);
576             }
577             catch (Exception e) {
578                 throw processException(e);
579             }
580             finally {
581                 if (list == null) {
582                     list = new ArrayList<Organization>();
583                 }
584 
585                 cacheResult(list);
586 
587                 FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_OBC_COMPANYID,
588                     finderArgs, list);
589 
590                 closeSession(session);
591             }
592         }
593 
594         return list;
595     }
596 
597     public Organization findByCompanyId_First(long companyId,
598         OrderByComparator obc)
599         throws NoSuchOrganizationException, SystemException {
600         List<Organization> list = findByCompanyId(companyId, 0, 1, obc);
601 
602         if (list.isEmpty()) {
603             StringBuilder msg = new StringBuilder();
604 
605             msg.append("No Organization exists with the key {");
606 
607             msg.append("companyId=" + companyId);
608 
609             msg.append(StringPool.CLOSE_CURLY_BRACE);
610 
611             throw new NoSuchOrganizationException(msg.toString());
612         }
613         else {
614             return list.get(0);
615         }
616     }
617 
618     public Organization findByCompanyId_Last(long companyId,
619         OrderByComparator obc)
620         throws NoSuchOrganizationException, SystemException {
621         int count = countByCompanyId(companyId);
622 
623         List<Organization> list = findByCompanyId(companyId, count - 1, count,
624                 obc);
625 
626         if (list.isEmpty()) {
627             StringBuilder msg = new StringBuilder();
628 
629             msg.append("No Organization exists with the key {");
630 
631             msg.append("companyId=" + companyId);
632 
633             msg.append(StringPool.CLOSE_CURLY_BRACE);
634 
635             throw new NoSuchOrganizationException(msg.toString());
636         }
637         else {
638             return list.get(0);
639         }
640     }
641 
642     public Organization[] findByCompanyId_PrevAndNext(long organizationId,
643         long companyId, OrderByComparator obc)
644         throws NoSuchOrganizationException, SystemException {
645         Organization organization = findByPrimaryKey(organizationId);
646 
647         int count = countByCompanyId(companyId);
648 
649         Session session = null;
650 
651         try {
652             session = openSession();
653 
654             StringBuilder query = new StringBuilder();
655 
656             query.append(
657                 "SELECT organization FROM Organization organization WHERE ");
658 
659             query.append("organization.companyId = ?");
660 
661             query.append(" ");
662 
663             if (obc != null) {
664                 query.append("ORDER BY ");
665 
666                 String[] orderByFields = obc.getOrderByFields();
667 
668                 for (int i = 0; i < orderByFields.length; i++) {
669                     query.append("organization.");
670                     query.append(orderByFields[i]);
671 
672                     if (obc.isAscending()) {
673                         query.append(" ASC");
674                     }
675                     else {
676                         query.append(" DESC");
677                     }
678 
679                     if ((i + 1) < orderByFields.length) {
680                         query.append(", ");
681                     }
682                 }
683             }
684 
685             else {
686                 query.append("ORDER BY ");
687 
688                 query.append("organization.name ASC");
689             }
690 
691             Query q = session.createQuery(query.toString());
692 
693             QueryPos qPos = QueryPos.getInstance(q);
694 
695             qPos.add(companyId);
696 
697             Object[] objArray = QueryUtil.getPrevAndNext(q, count, obc,
698                     organization);
699 
700             Organization[] array = new OrganizationImpl[3];
701 
702             array[0] = (Organization)objArray[0];
703             array[1] = (Organization)objArray[1];
704             array[2] = (Organization)objArray[2];
705 
706             return array;
707         }
708         catch (Exception e) {
709             throw processException(e);
710         }
711         finally {
712             closeSession(session);
713         }
714     }
715 
716     public List<Organization> findByLocations(long companyId)
717         throws SystemException {
718         Object[] finderArgs = new Object[] { new Long(companyId) };
719 
720         List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_LOCATIONS,
721                 finderArgs, this);
722 
723         if (list == null) {
724             Session session = null;
725 
726             try {
727                 session = openSession();
728 
729                 StringBuilder query = new StringBuilder();
730 
731                 query.append(
732                     "SELECT organization FROM Organization organization WHERE ");
733 
734                 query.append("organization.companyId = ?");
735 
736                 query.append(" AND organization.parentOrganizationId != 0 ");
737 
738                 query.append("ORDER BY ");
739 
740                 query.append("organization.name ASC");
741 
742                 Query q = session.createQuery(query.toString());
743 
744                 QueryPos qPos = QueryPos.getInstance(q);
745 
746                 qPos.add(companyId);
747 
748                 list = q.list();
749             }
750             catch (Exception e) {
751                 throw processException(e);
752             }
753             finally {
754                 if (list == null) {
755                     list = new ArrayList<Organization>();
756                 }
757 
758                 cacheResult(list);
759 
760                 FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_LOCATIONS,
761                     finderArgs, list);
762 
763                 closeSession(session);
764             }
765         }
766 
767         return list;
768     }
769 
770     public List<Organization> findByLocations(long companyId, int start, int end)
771         throws SystemException {
772         return findByLocations(companyId, start, end, null);
773     }
774 
775     public List<Organization> findByLocations(long companyId, int start,
776         int end, OrderByComparator obc) throws SystemException {
777         Object[] finderArgs = new Object[] {
778                 new Long(companyId),
779                 
780                 String.valueOf(start), String.valueOf(end), String.valueOf(obc)
781             };
782 
783         List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_OBC_LOCATIONS,
784                 finderArgs, this);
785 
786         if (list == null) {
787             Session session = null;
788 
789             try {
790                 session = openSession();
791 
792                 StringBuilder query = new StringBuilder();
793 
794                 query.append(
795                     "SELECT organization FROM Organization organization WHERE ");
796 
797                 query.append("organization.companyId = ?");
798 
799                 query.append(" AND organization.parentOrganizationId != 0 ");
800 
801                 if (obc != null) {
802                     query.append("ORDER BY ");
803 
804                     String[] orderByFields = obc.getOrderByFields();
805 
806                     for (int i = 0; i < orderByFields.length; i++) {
807                         query.append("organization.");
808                         query.append(orderByFields[i]);
809 
810                         if (obc.isAscending()) {
811                             query.append(" ASC");
812                         }
813                         else {
814                             query.append(" DESC");
815                         }
816 
817                         if ((i + 1) < orderByFields.length) {
818                             query.append(", ");
819                         }
820                     }
821                 }
822 
823                 else {
824                     query.append("ORDER BY ");
825 
826                     query.append("organization.name ASC");
827                 }
828 
829                 Query q = session.createQuery(query.toString());
830 
831                 QueryPos qPos = QueryPos.getInstance(q);
832 
833                 qPos.add(companyId);
834 
835                 list = (List<Organization>)QueryUtil.list(q, getDialect(),
836                         start, end);
837             }
838             catch (Exception e) {
839                 throw processException(e);
840             }
841             finally {
842                 if (list == null) {
843                     list = new ArrayList<Organization>();
844                 }
845 
846                 cacheResult(list);
847 
848                 FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_OBC_LOCATIONS,
849                     finderArgs, list);
850 
851                 closeSession(session);
852             }
853         }
854 
855         return list;
856     }
857 
858     public Organization findByLocations_First(long companyId,
859         OrderByComparator obc)
860         throws NoSuchOrganizationException, SystemException {
861         List<Organization> list = findByLocations(companyId, 0, 1, obc);
862 
863         if (list.isEmpty()) {
864             StringBuilder msg = new StringBuilder();
865 
866             msg.append("No Organization exists with the key {");
867 
868             msg.append("companyId=" + companyId);
869 
870             msg.append(StringPool.CLOSE_CURLY_BRACE);
871 
872             throw new NoSuchOrganizationException(msg.toString());
873         }
874         else {
875             return list.get(0);
876         }
877     }
878 
879     public Organization findByLocations_Last(long companyId,
880         OrderByComparator obc)
881         throws NoSuchOrganizationException, SystemException {
882         int count = countByLocations(companyId);
883 
884         List<Organization> list = findByLocations(companyId, count - 1, count,
885                 obc);
886 
887         if (list.isEmpty()) {
888             StringBuilder msg = new StringBuilder();
889 
890             msg.append("No Organization exists with the key {");
891 
892             msg.append("companyId=" + companyId);
893 
894             msg.append(StringPool.CLOSE_CURLY_BRACE);
895 
896             throw new NoSuchOrganizationException(msg.toString());
897         }
898         else {
899             return list.get(0);
900         }
901     }
902 
903     public Organization[] findByLocations_PrevAndNext(long organizationId,
904         long companyId, OrderByComparator obc)
905         throws NoSuchOrganizationException, SystemException {
906         Organization organization = findByPrimaryKey(organizationId);
907 
908         int count = countByLocations(companyId);
909 
910         Session session = null;
911 
912         try {
913             session = openSession();
914 
915             StringBuilder query = new StringBuilder();
916 
917             query.append(
918                 "SELECT organization FROM Organization organization WHERE ");
919 
920             query.append("organization.companyId = ?");
921 
922             query.append(" AND organization.parentOrganizationId != 0 ");
923 
924             if (obc != null) {
925                 query.append("ORDER BY ");
926 
927                 String[] orderByFields = obc.getOrderByFields();
928 
929                 for (int i = 0; i < orderByFields.length; i++) {
930                     query.append("organization.");
931                     query.append(orderByFields[i]);
932 
933                     if (obc.isAscending()) {
934                         query.append(" ASC");
935                     }
936                     else {
937                         query.append(" DESC");
938                     }
939 
940                     if ((i + 1) < orderByFields.length) {
941                         query.append(", ");
942                     }
943                 }
944             }
945 
946             else {
947                 query.append("ORDER BY ");
948 
949                 query.append("organization.name ASC");
950             }
951 
952             Query q = session.createQuery(query.toString());
953 
954             QueryPos qPos = QueryPos.getInstance(q);
955 
956             qPos.add(companyId);
957 
958             Object[] objArray = QueryUtil.getPrevAndNext(q, count, obc,
959                     organization);
960 
961             Organization[] array = new OrganizationImpl[3];
962 
963             array[0] = (Organization)objArray[0];
964             array[1] = (Organization)objArray[1];
965             array[2] = (Organization)objArray[2];
966 
967             return array;
968         }
969         catch (Exception e) {
970             throw processException(e);
971         }
972         finally {
973             closeSession(session);
974         }
975     }
976 
977     public List<Organization> findByC_P(long companyId,
978         long parentOrganizationId) throws SystemException {
979         Object[] finderArgs = new Object[] {
980                 new Long(companyId), new Long(parentOrganizationId)
981             };
982 
983         List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_C_P,
984                 finderArgs, this);
985 
986         if (list == null) {
987             Session session = null;
988 
989             try {
990                 session = openSession();
991 
992                 StringBuilder query = new StringBuilder();
993 
994                 query.append(
995                     "SELECT organization FROM Organization organization WHERE ");
996 
997                 query.append("organization.companyId = ?");
998 
999                 query.append(" AND ");
1000
1001                query.append("organization.parentOrganizationId = ?");
1002
1003                query.append(" ");
1004
1005                query.append("ORDER BY ");
1006
1007                query.append("organization.name ASC");
1008
1009                Query q = session.createQuery(query.toString());
1010
1011                QueryPos qPos = QueryPos.getInstance(q);
1012
1013                qPos.add(companyId);
1014
1015                qPos.add(parentOrganizationId);
1016
1017                list = q.list();
1018            }
1019            catch (Exception e) {
1020                throw processException(e);
1021            }
1022            finally {
1023                if (list == null) {
1024                    list = new ArrayList<Organization>();
1025                }
1026
1027                cacheResult(list);
1028
1029                FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_C_P, finderArgs,
1030                    list);
1031
1032                closeSession(session);
1033            }
1034        }
1035
1036        return list;
1037    }
1038
1039    public List<Organization> findByC_P(long companyId,
1040        long parentOrganizationId, int start, int end)
1041        throws SystemException {
1042        return findByC_P(companyId, parentOrganizationId, start, end, null);
1043    }
1044
1045    public List<Organization> findByC_P(long companyId,
1046        long parentOrganizationId, int start, int end, OrderByComparator obc)
1047        throws SystemException {
1048        Object[] finderArgs = new Object[] {
1049                new Long(companyId), new Long(parentOrganizationId),
1050                
1051                String.valueOf(start), String.valueOf(end), String.valueOf(obc)
1052            };
1053
1054        List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_OBC_C_P,
1055                finderArgs, this);
1056
1057        if (list == null) {
1058            Session session = null;
1059
1060            try {
1061                session = openSession();
1062
1063                StringBuilder query = new StringBuilder();
1064
1065                query.append(
1066                    "SELECT organization FROM Organization organization WHERE ");
1067
1068                query.append("organization.companyId = ?");
1069
1070                query.append(" AND ");
1071
1072                query.append("organization.parentOrganizationId = ?");
1073
1074                query.append(" ");
1075
1076                if (obc != null) {
1077                    query.append("ORDER BY ");
1078
1079                    String[] orderByFields = obc.getOrderByFields();
1080
1081                    for (int i = 0; i < orderByFields.length; i++) {
1082                        query.append("organization.");
1083                        query.append(orderByFields[i]);
1084
1085                        if (obc.isAscending()) {
1086                            query.append(" ASC");
1087                        }
1088                        else {
1089                            query.append(" DESC");
1090                        }
1091
1092                        if ((i + 1) < orderByFields.length) {
1093                            query.append(", ");
1094                        }
1095                    }
1096                }
1097
1098                else {
1099                    query.append("ORDER BY ");
1100
1101                    query.append("organization.name ASC");
1102                }
1103
1104                Query q = session.createQuery(query.toString());
1105
1106                QueryPos qPos = QueryPos.getInstance(q);
1107
1108                qPos.add(companyId);
1109
1110                qPos.add(parentOrganizationId);
1111
1112                list = (List<Organization>)QueryUtil.list(q, getDialect(),
1113                        start, end);
1114            }
1115            catch (Exception e) {
1116                throw processException(e);
1117            }
1118            finally {
1119                if (list == null) {
1120                    list = new ArrayList<Organization>();
1121                }
1122
1123                cacheResult(list);
1124
1125                FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_OBC_C_P,
1126                    finderArgs, list);
1127
1128                closeSession(session);
1129            }
1130        }
1131
1132        return list;
1133    }
1134
1135    public Organization findByC_P_First(long companyId,
1136        long parentOrganizationId, OrderByComparator obc)
1137        throws NoSuchOrganizationException, SystemException {
1138        List<Organization> list = findByC_P(companyId, parentOrganizationId, 0,
1139                1, obc);
1140
1141        if (list.isEmpty()) {
1142            StringBuilder msg = new StringBuilder();
1143
1144            msg.append("No Organization exists with the key {");
1145
1146            msg.append("companyId=" + companyId);
1147
1148            msg.append(", ");
1149            msg.append("parentOrganizationId=" + parentOrganizationId);
1150
1151            msg.append(StringPool.CLOSE_CURLY_BRACE);
1152
1153            throw new NoSuchOrganizationException(msg.toString());
1154        }
1155        else {
1156            return list.get(0);
1157        }
1158    }
1159
1160    public Organization findByC_P_Last(long companyId,
1161        long parentOrganizationId, OrderByComparator obc)
1162        throws NoSuchOrganizationException, SystemException {
1163        int count = countByC_P(companyId, parentOrganizationId);
1164
1165        List<Organization> list = findByC_P(companyId, parentOrganizationId,
1166                count - 1, count, obc);
1167
1168        if (list.isEmpty()) {
1169            StringBuilder msg = new StringBuilder();
1170
1171            msg.append("No Organization exists with the key {");
1172
1173            msg.append("companyId=" + companyId);
1174
1175            msg.append(", ");
1176            msg.append("parentOrganizationId=" + parentOrganizationId);
1177
1178            msg.append(StringPool.CLOSE_CURLY_BRACE);
1179
1180            throw new NoSuchOrganizationException(msg.toString());
1181        }
1182        else {
1183            return list.get(0);
1184        }
1185    }
1186
1187    public Organization[] findByC_P_PrevAndNext(long organizationId,
1188        long companyId, long parentOrganizationId, OrderByComparator obc)
1189        throws NoSuchOrganizationException, SystemException {
1190        Organization organization = findByPrimaryKey(organizationId);
1191
1192        int count = countByC_P(companyId, parentOrganizationId);
1193
1194        Session session = null;
1195
1196        try {
1197            session = openSession();
1198
1199            StringBuilder query = new StringBuilder();
1200
1201            query.append(
1202                "SELECT organization FROM Organization organization WHERE ");
1203
1204            query.append("organization.companyId = ?");
1205
1206            query.append(" AND ");
1207
1208            query.append("organization.parentOrganizationId = ?");
1209
1210            query.append(" ");
1211
1212            if (obc != null) {
1213                query.append("ORDER BY ");
1214
1215                String[] orderByFields = obc.getOrderByFields();
1216
1217                for (int i = 0; i < orderByFields.length; i++) {
1218                    query.append("organization.");
1219                    query.append(orderByFields[i]);
1220
1221                    if (obc.isAscending()) {
1222                        query.append(" ASC");
1223                    }
1224                    else {
1225                        query.append(" DESC");
1226                    }
1227
1228                    if ((i + 1) < orderByFields.length) {
1229                        query.append(", ");
1230                    }
1231                }
1232            }
1233
1234            else {
1235                query.append("ORDER BY ");
1236
1237                query.append("organization.name ASC");
1238            }
1239
1240            Query q = session.createQuery(query.toString());
1241
1242            QueryPos qPos = QueryPos.getInstance(q);
1243
1244            qPos.add(companyId);
1245
1246            qPos.add(parentOrganizationId);
1247
1248            Object[] objArray = QueryUtil.getPrevAndNext(q, count, obc,
1249                    organization);
1250
1251            Organization[] array = new OrganizationImpl[3];
1252
1253            array[0] = (Organization)objArray[0];
1254            array[1] = (Organization)objArray[1];
1255            array[2] = (Organization)objArray[2];
1256
1257            return array;
1258        }
1259        catch (Exception e) {
1260            throw processException(e);
1261        }
1262        finally {
1263            closeSession(session);
1264        }
1265    }
1266
1267    public Organization findByC_N(long companyId, String name)
1268        throws NoSuchOrganizationException, SystemException {
1269        Organization organization = fetchByC_N(companyId, name);
1270
1271        if (organization == null) {
1272            StringBuilder msg = new StringBuilder();
1273
1274            msg.append("No Organization exists with the key {");
1275
1276            msg.append("companyId=" + companyId);
1277
1278            msg.append(", ");
1279            msg.append("name=" + name);
1280
1281            msg.append(StringPool.CLOSE_CURLY_BRACE);
1282
1283            if (_log.isWarnEnabled()) {
1284                _log.warn(msg.toString());
1285            }
1286
1287            throw new NoSuchOrganizationException(msg.toString());
1288        }
1289
1290        return organization;
1291    }
1292
1293    public Organization fetchByC_N(long companyId, String name)
1294        throws SystemException {
1295        return fetchByC_N(companyId, name, true);
1296    }
1297
1298    public Organization fetchByC_N(long companyId, String name,
1299        boolean retrieveFromCache) throws SystemException {
1300        Object[] finderArgs = new Object[] { new Long(companyId), name };
1301
1302        Object result = null;
1303
1304        if (retrieveFromCache) {
1305            result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_C_N,
1306                    finderArgs, this);
1307        }
1308
1309        if (result == null) {
1310            Session session = null;
1311
1312            try {
1313                session = openSession();
1314
1315                StringBuilder query = new StringBuilder();
1316
1317                query.append(
1318                    "SELECT organization FROM Organization organization WHERE ");
1319
1320                query.append("organization.companyId = ?");
1321
1322                query.append(" AND ");
1323
1324                if (name == null) {
1325                    query.append("organization.name IS NULL");
1326                }
1327                else {
1328                    query.append("organization.name = ?");
1329                }
1330
1331                query.append(" ");
1332
1333                query.append("ORDER BY ");
1334
1335                query.append("organization.name ASC");
1336
1337                Query q = session.createQuery(query.toString());
1338
1339                QueryPos qPos = QueryPos.getInstance(q);
1340
1341                qPos.add(companyId);
1342
1343                if (name != null) {
1344                    qPos.add(name);
1345                }
1346
1347                List<Organization> list = q.list();
1348
1349                result = list;
1350
1351                Organization organization = null;
1352
1353                if (list.isEmpty()) {
1354                    FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_N,
1355                        finderArgs, list);
1356                }
1357                else {
1358                    organization = list.get(0);
1359
1360                    cacheResult(organization);
1361
1362                    if ((organization.getCompanyId() != companyId) ||
1363                            (organization.getName() == null) ||
1364                            !organization.getName().equals(name)) {
1365                        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_N,
1366                            finderArgs, organization);
1367                    }
1368                }
1369
1370                return organization;
1371            }
1372            catch (Exception e) {
1373                throw processException(e);
1374            }
1375            finally {
1376                if (result == null) {
1377                    FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_C_N,
1378                        finderArgs, new ArrayList<Organization>());
1379                }
1380
1381                closeSession(session);
1382            }
1383        }
1384        else {
1385            if (result instanceof List) {
1386                return null;
1387            }
1388            else {
1389                return (Organization)result;
1390            }
1391        }
1392    }
1393
1394    public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery)
1395        throws SystemException {
1396        Session session = null;
1397
1398        try {
1399            session = openSession();
1400
1401            dynamicQuery.compile(session);
1402
1403            return dynamicQuery.list();
1404        }
1405        catch (Exception e) {
1406            throw processException(e);
1407        }
1408        finally {
1409            closeSession(session);
1410        }
1411    }
1412
1413    public List<Object> findWithDynamicQuery(DynamicQuery dynamicQuery,
1414        int start, int end) throws SystemException {
1415        Session session = null;
1416
1417        try {
1418            session = openSession();
1419
1420            dynamicQuery.setLimit(start, end);
1421
1422            dynamicQuery.compile(session);
1423
1424            return dynamicQuery.list();
1425        }
1426        catch (Exception e) {
1427            throw processException(e);
1428        }
1429        finally {
1430            closeSession(session);
1431        }
1432    }
1433
1434    public List<Organization> findAll() throws SystemException {
1435        return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
1436    }
1437
1438    public List<Organization> findAll(int start, int end)
1439        throws SystemException {
1440        return findAll(start, end, null);
1441    }
1442
1443    public List<Organization> findAll(int start, int end, OrderByComparator obc)
1444        throws SystemException {
1445        Object[] finderArgs = new Object[] {
1446                String.valueOf(start), String.valueOf(end), String.valueOf(obc)
1447            };
1448
1449        List<Organization> list = (List<Organization>)FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
1450                finderArgs, this);
1451
1452        if (list == null) {
1453            Session session = null;
1454
1455            try {
1456                session = openSession();
1457
1458                StringBuilder query = new StringBuilder();
1459
1460                query.append(
1461                    "SELECT organization FROM Organization organization ");
1462
1463                if (obc != null) {
1464                    query.append("ORDER BY ");
1465
1466                    String[] orderByFields = obc.getOrderByFields();
1467
1468                    for (int i = 0; i < orderByFields.length; i++) {
1469                        query.append("organization.");
1470                        query.append(orderByFields[i]);
1471
1472                        if (obc.isAscending()) {
1473                            query.append(" ASC");
1474                        }
1475                        else {
1476                            query.append(" DESC");
1477                        }
1478
1479                        if ((i + 1) < orderByFields.length) {
1480                            query.append(", ");
1481                        }
1482                    }
1483                }
1484
1485                else {
1486                    query.append("ORDER BY ");
1487
1488                    query.append("organization.name ASC");
1489                }
1490
1491                Query q = session.createQuery(query.toString());
1492
1493                if (obc == null) {
1494                    list = (List<Organization>)QueryUtil.list(q, getDialect(),
1495                            start, end, false);
1496
1497                    Collections.sort(list);
1498                }
1499                else {
1500                    list = (List<Organization>)QueryUtil.list(q, getDialect(),
1501                            start, end);
1502                }
1503            }
1504            catch (Exception e) {
1505                throw processException(e);
1506            }
1507            finally {
1508                if (list == null) {
1509                    list = new ArrayList<Organization>();
1510                }
1511
1512                cacheResult(list);
1513
1514                FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs, list);
1515
1516                closeSession(session);
1517            }
1518        }
1519
1520        return list;
1521    }
1522
1523    public void removeByCompanyId(long companyId) throws SystemException {
1524        for (Organization organization : findByCompanyId(companyId)) {
1525            remove(organization);
1526        }
1527    }
1528
1529    public void removeByLocations(long companyId) throws SystemException {
1530        for (Organization organization : findByLocations(companyId)) {
1531            remove(organization);
1532        }
1533    }
1534
1535    public void removeByC_P(long companyId, long parentOrganizationId)
1536        throws SystemException {
1537        for (Organization organization : findByC_P(companyId,
1538                parentOrganizationId)) {
1539            remove(organization);
1540        }
1541    }
1542
1543    public void removeByC_N(long companyId, String name)
1544        throws NoSuchOrganizationException, SystemException {
1545        Organization organization = findByC_N(companyId, name);
1546
1547        remove(organization);
1548    }
1549
1550    public void removeAll() throws SystemException {
1551        for (Organization organization : findAll()) {
1552            remove(organization);
1553        }
1554    }
1555
1556    public int countByCompanyId(long companyId) throws SystemException {
1557        Object[] finderArgs = new Object[] { new Long(companyId) };
1558
1559        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_COMPANYID,
1560                finderArgs, this);
1561
1562        if (count == null) {
1563            Session session = null;
1564
1565            try {
1566                session = openSession();
1567
1568                StringBuilder query = new StringBuilder();
1569
1570                query.append("SELECT COUNT(organization) ");
1571                query.append("FROM Organization organization WHERE ");
1572
1573                query.append("organization.companyId = ?");
1574
1575                query.append(" ");
1576
1577                Query q = session.createQuery(query.toString());
1578
1579                QueryPos qPos = QueryPos.getInstance(q);
1580
1581                qPos.add(companyId);
1582
1583                count = (Long)q.uniqueResult();
1584            }
1585            catch (Exception e) {
1586                throw processException(e);
1587            }
1588            finally {
1589                if (count == null) {
1590                    count = Long.valueOf(0);
1591                }
1592
1593                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_COMPANYID,
1594                    finderArgs, count);
1595
1596                closeSession(session);
1597            }
1598        }
1599
1600        return count.intValue();
1601    }
1602
1603    public int countByLocations(long companyId) throws SystemException {
1604        Object[] finderArgs = new Object[] { new Long(companyId) };
1605
1606        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_LOCATIONS,
1607                finderArgs, this);
1608
1609        if (count == null) {
1610            Session session = null;
1611
1612            try {
1613                session = openSession();
1614
1615                StringBuilder query = new StringBuilder();
1616
1617                query.append("SELECT COUNT(organization) ");
1618                query.append("FROM Organization organization WHERE ");
1619
1620                query.append("organization.companyId = ?");
1621
1622                query.append(" AND organization.parentOrganizationId != 0 ");
1623
1624                Query q = session.createQuery(query.toString());
1625
1626                QueryPos qPos = QueryPos.getInstance(q);
1627
1628                qPos.add(companyId);
1629
1630                count = (Long)q.uniqueResult();
1631            }
1632            catch (Exception e) {
1633                throw processException(e);
1634            }
1635            finally {
1636                if (count == null) {
1637                    count = Long.valueOf(0);
1638                }
1639
1640                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_LOCATIONS,
1641                    finderArgs, count);
1642
1643                closeSession(session);
1644            }
1645        }
1646
1647        return count.intValue();
1648    }
1649
1650    public int countByC_P(long companyId, long parentOrganizationId)
1651        throws SystemException {
1652        Object[] finderArgs = new Object[] {
1653                new Long(companyId), new Long(parentOrganizationId)
1654            };
1655
1656        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_C_P,
1657                finderArgs, this);
1658
1659        if (count == null) {
1660            Session session = null;
1661
1662            try {
1663                session = openSession();
1664
1665                StringBuilder query = new StringBuilder();
1666
1667                query.append("SELECT COUNT(organization) ");
1668                query.append("FROM Organization organization WHERE ");
1669
1670                query.append("organization.companyId = ?");
1671
1672                query.append(" AND ");
1673
1674                query.append("organization.parentOrganizationId = ?");
1675
1676                query.append(" ");
1677
1678                Query q = session.createQuery(query.toString());
1679
1680                QueryPos qPos = QueryPos.getInstance(q);
1681
1682                qPos.add(companyId);
1683
1684                qPos.add(parentOrganizationId);
1685
1686                count = (Long)q.uniqueResult();
1687            }
1688            catch (Exception e) {
1689                throw processException(e);
1690            }
1691            finally {
1692                if (count == null) {
1693                    count = Long.valueOf(0);
1694                }
1695
1696                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_C_P, finderArgs,
1697                    count);
1698
1699                closeSession(session);
1700            }
1701        }
1702
1703        return count.intValue();
1704    }
1705
1706    public int countByC_N(long companyId, String name)
1707        throws SystemException {
1708        Object[] finderArgs = new Object[] { new Long(companyId), name };
1709
1710        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_C_N,
1711                finderArgs, this);
1712
1713        if (count == null) {
1714            Session session = null;
1715
1716            try {
1717                session = openSession();
1718
1719                StringBuilder query = new StringBuilder();
1720
1721                query.append("SELECT COUNT(organization) ");
1722                query.append("FROM Organization organization WHERE ");
1723
1724                query.append("organization.companyId = ?");
1725
1726                query.append(" AND ");
1727
1728                if (name == null) {
1729                    query.append("organization.name IS NULL");
1730                }
1731                else {
1732                    query.append("organization.name = ?");
1733                }
1734
1735                query.append(" ");
1736
1737                Query q = session.createQuery(query.toString());
1738
1739                QueryPos qPos = QueryPos.getInstance(q);
1740
1741                qPos.add(companyId);
1742
1743                if (name != null) {
1744                    qPos.add(name);
1745                }
1746
1747                count = (Long)q.uniqueResult();
1748            }
1749            catch (Exception e) {
1750                throw processException(e);
1751            }
1752            finally {
1753                if (count == null) {
1754                    count = Long.valueOf(0);
1755                }
1756
1757                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_C_N, finderArgs,
1758                    count);
1759
1760                closeSession(session);
1761            }
1762        }
1763
1764        return count.intValue();
1765    }
1766
1767    public int countAll() throws SystemException {
1768        Object[] finderArgs = new Object[0];
1769
1770        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
1771                finderArgs, this);
1772
1773        if (count == null) {
1774            Session session = null;
1775
1776            try {
1777                session = openSession();
1778
1779                Query q = session.createQuery(
1780                        "SELECT COUNT(organization) FROM Organization organization");
1781
1782                count = (Long)q.uniqueResult();
1783            }
1784            catch (Exception e) {
1785                throw processException(e);
1786            }
1787            finally {
1788                if (count == null) {
1789                    count = Long.valueOf(0);
1790                }
1791
1792                FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
1793                    count);
1794
1795                closeSession(session);
1796            }
1797        }
1798
1799        return count.intValue();
1800    }
1801
1802    public List<com.liferay.portal.model.Group> getGroups(long pk)
1803        throws SystemException {
1804        return getGroups(pk, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
1805    }
1806
1807    public List<com.liferay.portal.model.Group> getGroups(long pk, int start,
1808        int end) throws SystemException {
1809        return getGroups(pk, start, end, null);
1810    }
1811
1812    public static final FinderPath FINDER_PATH_GET_GROUPS = new FinderPath(com.liferay.portal.model.impl.GroupModelImpl.ENTITY_CACHE_ENABLED,
1813            OrganizationModelImpl.FINDER_CACHE_ENABLED_GROUPS_ORGS,
1814            "Groups_Orgs", "getGroups",
1815            new String[] {
1816                Long.class.getName(), "java.lang.Integer", "java.lang.Integer",
1817                "com.liferay.portal.kernel.util.OrderByComparator"
1818            });
1819
1820    public List<com.liferay.portal.model.Group> getGroups(long pk, int start,
1821        int end, OrderByComparator obc) throws SystemException {
1822        Object[] finderArgs = new Object[] {
1823                new Long(pk), String.valueOf(start), String.valueOf(end),
1824                String.valueOf(obc)
1825            };
1826
1827        List<com.liferay.portal.model.Group> list = (List<com.liferay.portal.model.Group>)FinderCacheUtil.getResult(FINDER_PATH_GET_GROUPS,
1828                finderArgs, this);
1829
1830        if (list == null) {
1831            Session session = null;
1832
1833            try {
1834                session = openSession();
1835
1836                StringBuilder sb = new StringBuilder();
1837
1838                sb.append(_SQL_GETGROUPS);
1839
1840                if (obc != null) {
1841                    sb.append("ORDER BY ");
1842                    sb.append(obc.getOrderBy());
1843                }
1844
1845                else {
1846                    sb.append("ORDER BY ");
1847
1848                    sb.append("Group_.name ASC");
1849                }
1850
1851                String sql = sb.toString();
1852
1853                SQLQuery q = session.createSQLQuery(sql);
1854
1855                q.addEntity("Group_",
1856                    com.liferay.portal.model.impl.GroupImpl.class);
1857
1858                QueryPos qPos = QueryPos.getInstance(q);
1859
1860                qPos.add(pk);
1861
1862                list = (List<com.liferay.portal.model.Group>)QueryUtil.list(q,
1863                        getDialect(), start, end);
1864            }
1865            catch (Exception e) {
1866                throw processException(e);
1867            }
1868            finally {
1869                if (list == null) {
1870                    list = new ArrayList<com.liferay.portal.model.Group>();
1871                }
1872
1873                groupPersistence.cacheResult(list);
1874
1875                FinderCacheUtil.putResult(FINDER_PATH_GET_GROUPS, finderArgs,
1876                    list);
1877
1878                closeSession(session);
1879            }
1880        }
1881
1882        return list;
1883    }
1884
1885    public static final FinderPath FINDER_PATH_GET_GROUPS_SIZE = new FinderPath(com.liferay.portal.model.impl.GroupModelImpl.ENTITY_CACHE_ENABLED,
1886            OrganizationModelImpl.FINDER_CACHE_ENABLED_GROUPS_ORGS,
1887            "Groups_Orgs", "getGroupsSize",
1888            new String[] { Long.class.getName() });
1889
1890    public int getGroupsSize(long pk) throws SystemException {
1891        Object[] finderArgs = new Object[] { new Long(pk) };
1892
1893        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_GET_GROUPS_SIZE,
1894                finderArgs, this);
1895
1896        if (count == null) {
1897            Session session = null;
1898
1899            try {
1900                session = openSession();
1901
1902                SQLQuery q = session.createSQLQuery(_SQL_GETGROUPSSIZE);
1903
1904                q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
1905
1906                QueryPos qPos = QueryPos.getInstance(q);
1907
1908                qPos.add(pk);
1909
1910                count = (Long)q.uniqueResult();
1911            }
1912            catch (Exception e) {
1913                throw processException(e);
1914            }
1915            finally {
1916                if (count == null) {
1917                    count = Long.valueOf(0);
1918                }
1919
1920                FinderCacheUtil.putResult(FINDER_PATH_GET_GROUPS_SIZE,
1921                    finderArgs, count);
1922
1923                closeSession(session);
1924            }
1925        }
1926
1927        return count.intValue();
1928    }
1929
1930    public static final FinderPath FINDER_PATH_CONTAINS_GROUP = new FinderPath(com.liferay.portal.model.impl.GroupModelImpl.ENTITY_CACHE_ENABLED,
1931            OrganizationModelImpl.FINDER_CACHE_ENABLED_GROUPS_ORGS,
1932            "Groups_Orgs", "containsGroup",
1933            new String[] { Long.class.getName(), Long.class.getName() });
1934
1935    public boolean containsGroup(long pk, long groupPK)
1936        throws SystemException {
1937        Object[] finderArgs = new Object[] { new Long(pk), new Long(groupPK) };
1938
1939        Boolean value = (Boolean)FinderCacheUtil.getResult(FINDER_PATH_CONTAINS_GROUP,
1940                finderArgs, this);
1941
1942        if (value == null) {
1943            try {
1944                value = Boolean.valueOf(containsGroup.contains(pk, groupPK));
1945            }
1946            catch (Exception e) {
1947                throw processException(e);
1948            }
1949            finally {
1950                if (value == null) {
1951                    value = Boolean.FALSE;
1952                }
1953
1954                FinderCacheUtil.putResult(FINDER_PATH_CONTAINS_GROUP,
1955                    finderArgs, value);
1956            }
1957        }
1958
1959        return value.booleanValue();
1960    }
1961
1962    public boolean containsGroups(long pk) throws SystemException {
1963        if (getGroupsSize(pk) > 0) {
1964            return true;
1965        }
1966        else {
1967            return false;
1968        }
1969    }
1970
1971    public void addGroup(long pk, long groupPK) throws SystemException {
1972        try {
1973            addGroup.add(pk, groupPK);
1974        }
1975        catch (Exception e) {
1976            throw processException(e);
1977        }
1978        finally {
1979            FinderCacheUtil.clearCache("Groups_Orgs");
1980        }
1981    }
1982
1983    public void addGroup(long pk, com.liferay.portal.model.Group group)
1984        throws SystemException {
1985        try {
1986            addGroup.add(pk, group.getPrimaryKey());
1987        }
1988        catch (Exception e) {
1989            throw processException(e);
1990        }
1991        finally {
1992            FinderCacheUtil.clearCache("Groups_Orgs");
1993        }
1994    }
1995
1996    public void addGroups(long pk, long[] groupPKs) throws SystemException {
1997        try {
1998            for (long groupPK : groupPKs) {
1999                addGroup.add(pk, groupPK);
2000            }
2001        }
2002        catch (Exception e) {
2003            throw processException(e);
2004        }
2005        finally {
2006            FinderCacheUtil.clearCache("Groups_Orgs");
2007        }
2008    }
2009
2010    public void addGroups(long pk, List<com.liferay.portal.model.Group> groups)
2011        throws SystemException {
2012        try {
2013            for (com.liferay.portal.model.Group group : groups) {
2014                addGroup.add(pk, group.getPrimaryKey());
2015            }
2016        }
2017        catch (Exception e) {
2018            throw processException(e);
2019        }
2020        finally {
2021            FinderCacheUtil.clearCache("Groups_Orgs");
2022        }
2023    }
2024
2025    public void clearGroups(long pk) throws SystemException {
2026        try {
2027            clearGroups.clear(pk);
2028        }
2029        catch (Exception e) {
2030            throw processException(e);
2031        }
2032        finally {
2033            FinderCacheUtil.clearCache("Groups_Orgs");
2034        }
2035    }
2036
2037    public void removeGroup(long pk, long groupPK) throws SystemException {
2038        try {
2039            removeGroup.remove(pk, groupPK);
2040        }
2041        catch (Exception e) {
2042            throw processException(e);
2043        }
2044        finally {
2045            FinderCacheUtil.clearCache("Groups_Orgs");
2046        }
2047    }
2048
2049    public void removeGroup(long pk, com.liferay.portal.model.Group group)
2050        throws SystemException {
2051        try {
2052            removeGroup.remove(pk, group.getPrimaryKey());
2053        }
2054        catch (Exception e) {
2055            throw processException(e);
2056        }
2057        finally {
2058            FinderCacheUtil.clearCache("Groups_Orgs");
2059        }
2060    }
2061
2062    public void removeGroups(long pk, long[] groupPKs)
2063        throws SystemException {
2064        try {
2065            for (long groupPK : groupPKs) {
2066                removeGroup.remove(pk, groupPK);
2067            }
2068        }
2069        catch (Exception e) {
2070            throw processException(e);
2071        }
2072        finally {
2073            FinderCacheUtil.clearCache("Groups_Orgs");
2074        }
2075    }
2076
2077    public void removeGroups(long pk,
2078        List<com.liferay.portal.model.Group> groups) throws SystemException {
2079        try {
2080            for (com.liferay.portal.model.Group group : groups) {
2081                removeGroup.remove(pk, group.getPrimaryKey());
2082            }
2083        }
2084        catch (Exception e) {
2085            throw processException(e);
2086        }
2087        finally {
2088            FinderCacheUtil.clearCache("Groups_Orgs");
2089        }
2090    }
2091
2092    public void setGroups(long pk, long[] groupPKs) throws SystemException {
2093        try {
2094            clearGroups.clear(pk);
2095
2096            for (long groupPK : groupPKs) {
2097                addGroup.add(pk, groupPK);
2098            }
2099        }
2100        catch (Exception e) {
2101            throw processException(e);
2102        }
2103        finally {
2104            FinderCacheUtil.clearCache("Groups_Orgs");
2105        }
2106    }
2107
2108    public void setGroups(long pk, List<com.liferay.portal.model.Group> groups)
2109        throws SystemException {
2110        try {
2111            clearGroups.clear(pk);
2112
2113            for (com.liferay.portal.model.Group group : groups) {
2114                addGroup.add(pk, group.getPrimaryKey());
2115            }
2116        }
2117        catch (Exception e) {
2118            throw processException(e);
2119        }
2120        finally {
2121            FinderCacheUtil.clearCache("Groups_Orgs");
2122        }
2123    }
2124
2125    public List<com.liferay.portal.model.User> getUsers(long pk)
2126        throws SystemException {
2127        return getUsers(pk, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
2128    }
2129
2130    public List<com.liferay.portal.model.User> getUsers(long pk, int start,
2131        int end) throws SystemException {
2132        return getUsers(pk, start, end, null);
2133    }
2134
2135    public static final FinderPath FINDER_PATH_GET_USERS = new FinderPath(com.liferay.portal.model.impl.UserModelImpl.ENTITY_CACHE_ENABLED,
2136            OrganizationModelImpl.FINDER_CACHE_ENABLED_USERS_ORGS,
2137            "Users_Orgs", "getUsers",
2138            new String[] {
2139                Long.class.getName(), "java.lang.Integer", "java.lang.Integer",
2140                "com.liferay.portal.kernel.util.OrderByComparator"
2141            });
2142
2143    public List<com.liferay.portal.model.User> getUsers(long pk, int start,
2144        int end, OrderByComparator obc) throws SystemException {
2145        Object[] finderArgs = new Object[] {
2146                new Long(pk), String.valueOf(start), String.valueOf(end),
2147                String.valueOf(obc)
2148            };
2149
2150        List<com.liferay.portal.model.User> list = (List<com.liferay.portal.model.User>)FinderCacheUtil.getResult(FINDER_PATH_GET_USERS,
2151                finderArgs, this);
2152
2153        if (list == null) {
2154            Session session = null;
2155
2156            try {
2157                session = openSession();
2158
2159                StringBuilder sb = new StringBuilder();
2160
2161                sb.append(_SQL_GETUSERS);
2162
2163                if (obc != null) {
2164                    sb.append("ORDER BY ");
2165                    sb.append(obc.getOrderBy());
2166                }
2167
2168                String sql = sb.toString();
2169
2170                SQLQuery q = session.createSQLQuery(sql);
2171
2172                q.addEntity("User_",
2173                    com.liferay.portal.model.impl.UserImpl.class);
2174
2175                QueryPos qPos = QueryPos.getInstance(q);
2176
2177                qPos.add(pk);
2178
2179                list = (List<com.liferay.portal.model.User>)QueryUtil.list(q,
2180                        getDialect(), start, end);
2181            }
2182            catch (Exception e) {
2183                throw processException(e);
2184            }
2185            finally {
2186                if (list == null) {
2187                    list = new ArrayList<com.liferay.portal.model.User>();
2188                }
2189
2190                userPersistence.cacheResult(list);
2191
2192                FinderCacheUtil.putResult(FINDER_PATH_GET_USERS, finderArgs,
2193                    list);
2194
2195                closeSession(session);
2196            }
2197        }
2198
2199        return list;
2200    }
2201
2202    public static final FinderPath FINDER_PATH_GET_USERS_SIZE = new FinderPath(com.liferay.portal.model.impl.UserModelImpl.ENTITY_CACHE_ENABLED,
2203            OrganizationModelImpl.FINDER_CACHE_ENABLED_USERS_ORGS,
2204            "Users_Orgs", "getUsersSize", new String[] { Long.class.getName() });
2205
2206    public int getUsersSize(long pk) throws SystemException {
2207        Object[] finderArgs = new Object[] { new Long(pk) };
2208
2209        Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_GET_USERS_SIZE,
2210                finderArgs, this);
2211
2212        if (count == null) {
2213            Session session = null;
2214
2215            try {
2216                session = openSession();
2217
2218                SQLQuery q = session.createSQLQuery(_SQL_GETUSERSSIZE);
2219
2220                q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
2221
2222                QueryPos qPos = QueryPos.getInstance(q);
2223
2224                qPos.add(pk);
2225
2226                count = (Long)q.uniqueResult();
2227            }
2228            catch (Exception e) {
2229                throw processException(e);
2230            }
2231            finally {
2232                if (count == null) {
2233                    count = Long.valueOf(0);
2234                }
2235
2236                FinderCacheUtil.putResult(FINDER_PATH_GET_USERS_SIZE,
2237                    finderArgs, count);
2238
2239                closeSession(session);
2240            }
2241        }
2242
2243        return count.intValue();
2244    }
2245
2246    public static final FinderPath FINDER_PATH_CONTAINS_USER = new FinderPath(com.liferay.portal.model.impl.UserModelImpl.ENTITY_CACHE_ENABLED,
2247            OrganizationModelImpl.FINDER_CACHE_ENABLED_USERS_ORGS,
2248            "Users_Orgs", "containsUser",
2249            new String[] { Long.class.getName(), Long.class.getName() });
2250
2251    public boolean containsUser(long pk, long userPK) throws SystemException {
2252        Object[] finderArgs = new Object[] { new Long(pk), new Long(userPK) };
2253
2254        Boolean value = (Boolean)FinderCacheUtil.getResult(FINDER_PATH_CONTAINS_USER,
2255                finderArgs, this);
2256
2257        if (value == null) {
2258            try {
2259                value = Boolean.valueOf(containsUser.contains(pk, userPK));
2260            }
2261            catch (Exception e) {
2262                throw processException(e);
2263            }
2264            finally {
2265                if (value == null) {
2266                    value = Boolean.FALSE;
2267                }
2268
2269                FinderCacheUtil.putResult(FINDER_PATH_CONTAINS_USER,
2270                    finderArgs, value);
2271            }
2272        }
2273
2274        return value.booleanValue();
2275    }
2276
2277    public boolean containsUsers(long pk) throws SystemException {
2278        if (getUsersSize(pk) > 0) {
2279            return true;
2280        }
2281        else {
2282            return false;
2283        }
2284    }
2285
2286    public void addUser(long pk, long userPK) throws SystemException {
2287        try {
2288            addUser.add(pk, userPK);
2289        }
2290        catch (Exception e) {
2291            throw processException(e);
2292        }
2293        finally {
2294            FinderCacheUtil.clearCache("Users_Orgs");
2295        }
2296    }
2297
2298    public void addUser(long pk, com.liferay.portal.model.User user)
2299        throws SystemException {
2300        try {
2301            addUser.add(pk, user.getPrimaryKey());
2302        }
2303        catch (Exception e) {
2304            throw processException(e);
2305        }
2306        finally {
2307            FinderCacheUtil.clearCache("Users_Orgs");
2308        }
2309    }
2310
2311    public void addUsers(long pk, long[] userPKs) throws SystemException {
2312        try {
2313            for (long userPK : userPKs) {
2314                addUser.add(pk, userPK);
2315            }
2316        }
2317        catch (Exception e) {
2318            throw processException(e);
2319        }
2320        finally {
2321            FinderCacheUtil.clearCache("Users_Orgs");
2322        }
2323    }
2324
2325    public void addUsers(long pk, List<com.liferay.portal.model.User> users)
2326        throws SystemException {
2327        try {
2328            for (com.liferay.portal.model.User user : users) {
2329                addUser.add(pk, user.getPrimaryKey());
2330            }
2331        }
2332        catch (Exception e) {
2333            throw processException(e);
2334        }
2335        finally {
2336            FinderCacheUtil.clearCache("Users_Orgs");
2337        }
2338    }
2339
2340    public void clearUsers(long pk) throws SystemException {
2341        try {
2342            clearUsers.clear(pk);
2343        }
2344        catch (Exception e) {
2345            throw processException(e);
2346        }
2347        finally {
2348            FinderCacheUtil.clearCache("Users_Orgs");
2349        }
2350    }
2351
2352    public void removeUser(long pk, long userPK) throws SystemException {
2353        try {
2354            removeUser.remove(pk, userPK);
2355        }
2356        catch (Exception e) {
2357            throw processException(e);
2358        }
2359        finally {
2360            FinderCacheUtil.clearCache("Users_Orgs");
2361        }
2362    }
2363
2364    public void removeUser(long pk, com.liferay.portal.model.User user)
2365        throws SystemException {
2366        try {
2367            removeUser.remove(pk, user.getPrimaryKey());
2368        }
2369        catch (Exception e) {
2370            throw processException(e);
2371        }
2372        finally {
2373            FinderCacheUtil.clearCache("Users_Orgs");
2374        }
2375    }
2376
2377    public void removeUsers(long pk, long[] userPKs) throws SystemException {
2378        try {
2379            for (long userPK : userPKs) {
2380                removeUser.remove(pk, userPK);
2381            }
2382        }
2383        catch (Exception e) {
2384            throw processException(e);
2385        }
2386        finally {
2387            FinderCacheUtil.clearCache("Users_Orgs");
2388        }
2389    }
2390
2391    public void removeUsers(long pk, List<com.liferay.portal.model.User> users)
2392        throws SystemException {
2393        try {
2394            for (com.liferay.portal.model.User user : users) {
2395                removeUser.remove(pk, user.getPrimaryKey());
2396            }
2397        }
2398        catch (Exception e) {
2399            throw processException(e);
2400        }
2401        finally {
2402            FinderCacheUtil.clearCache("Users_Orgs");
2403        }
2404    }
2405
2406    public void setUsers(long pk, long[] userPKs) throws SystemException {
2407        try {
2408            clearUsers.clear(pk);
2409
2410            for (long userPK : userPKs) {
2411                addUser.add(pk, userPK);
2412            }
2413        }
2414        catch (Exception e) {
2415            throw processException(e);
2416        }
2417        finally {
2418            FinderCacheUtil.clearCache("Users_Orgs");
2419        }
2420    }
2421
2422    public void setUsers(long pk, List<com.liferay.portal.model.User> users)
2423        throws SystemException {
2424        try {
2425            clearUsers.clear(pk);
2426
2427            for (com.liferay.portal.model.User user : users) {
2428                addUser.add(pk, user.getPrimaryKey());
2429            }
2430        }
2431        catch (Exception e) {
2432            throw processException(e);
2433        }
2434        finally {
2435            FinderCacheUtil.clearCache("Users_Orgs");
2436        }
2437    }
2438
2439    public void rebuildTree(long companyId, boolean force)
2440        throws SystemException {
2441        if (force || (countOrphanTreeNodes(companyId) > 0)) {
2442            rebuildTree(companyId, 0, 1);
2443
2444            CacheRegistry.clear(OrganizationImpl.class.getName());
2445            EntityCacheUtil.clearCache(OrganizationImpl.class.getName());
2446            FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
2447            FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
2448        }
2449    }
2450
2451    protected long countOrphanTreeNodes(long companyId)
2452        throws SystemException {
2453        Session session = null;
2454
2455        try {
2456            session = openSession();
2457
2458            SQLQuery q = session.createSQLQuery(
2459                    "SELECT COUNT(*) AS COUNT_VALUE FROM Organization_ WHERE companyId = ? AND (leftOrganizationId = 0 OR leftOrganizationId IS NULL OR rightOrganizationId = 0 OR rightOrganizationId IS NULL)");
2460
2461            q.addScalar(COUNT_COLUMN_NAME, Type.LONG);
2462
2463            QueryPos qPos = QueryPos.getInstance(q);
2464
2465            qPos.add(companyId);
2466
2467            return (Long)q.uniqueResult();
2468        }
2469        catch (Exception e) {
2470            throw processException(e);
2471        }
2472        finally {
2473            closeSession(session);
2474        }
2475    }
2476
2477    protected void expandTree(Organization organization)
2478        throws SystemException {
2479        long companyId = organization.getCompanyId();
2480
2481        long lastRightOrganizationId = getLastRightOrganizationId(companyId,
2482                organization.getParentOrganizationId());
2483
2484        long leftOrganizationId = 2;
2485        long rightOrganizationId = 3;
2486
2487        if (lastRightOrganizationId > 0) {
2488            leftOrganizationId = lastRightOrganizationId + 1;
2489            rightOrganizationId = lastRightOrganizationId + 2;
2490
2491            expandTreeLeftOrganizationId.expand(companyId,
2492                lastRightOrganizationId);
2493            expandTreeRightOrganizationId.expand(companyId,
2494                lastRightOrganizationId);
2495
2496            CacheRegistry.clear(OrganizationImpl.class.getName());
2497            EntityCacheUtil.clearCache(OrganizationImpl.class.getName());
2498            FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
2499            FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
2500        }
2501
2502        organization.setLeftOrganizationId(leftOrganizationId);
2503        organization.setRightOrganizationId(rightOrganizationId);
2504    }
2505
2506    protected long getLastRightOrganizationId(long companyId,
2507        long parentOrganizationId) throws SystemException {
2508        Session session = null;
2509
2510        try {
2511            session = openSession();
2512
2513            SQLQuery q = session.createSQLQuery(
2514                    "SELECT rightOrganizationId FROM Organization_ WHERE (companyId = ?) AND (parentOrganizationId = ?) ORDER BY rightOrganizationId DESC");
2515
2516            q.addScalar("rightOrganizationId", Type.LONG);
2517
2518            QueryPos qPos = QueryPos.getInstance(q);
2519
2520            qPos.add(companyId);
2521            qPos.add(parentOrganizationId);
2522
2523            List<Long> list = (List<Long>)QueryUtil.list(q, getDialect(), 0, 1);
2524
2525            if (list.isEmpty()) {
2526                if (parentOrganizationId > 0) {
2527                    Organization parentOrganization = findByPrimaryKey(parentOrganizationId);
2528
2529                    return parentOrganization.getLeftOrganizationId();
2530                }
2531
2532                return 0;
2533            }
2534            else {
2535                return list.get(0);
2536            }
2537        }
2538        catch (Exception e) {
2539            throw processException(e);
2540        }
2541        finally {
2542            closeSession(session);
2543        }
2544    }
2545
2546    protected long rebuildTree(long companyId, long parentOrganizationId,
2547        long leftOrganizationId) throws SystemException {
2548        List<Long> organizationIds = null;
2549
2550        Session session = null;
2551
2552        try {
2553            session = openSession();
2554
2555            SQLQuery q = session.createSQLQuery(
2556                    "SELECT organizationId FROM Organization_ WHERE companyId = ? AND parentOrganizationId = ? ORDER BY organizationId ASC");
2557
2558            q.addScalar("organizationId", Type.LONG);
2559
2560            QueryPos qPos = QueryPos.getInstance(q);
2561
2562            qPos.add(companyId);
2563            qPos.add(parentOrganizationId);
2564
2565            organizationIds = q.list();
2566        }
2567        catch (Exception e) {
2568            throw processException(e);
2569        }
2570        finally {
2571            closeSession(session);
2572        }
2573
2574        long rightOrganizationId = leftOrganizationId + 1;
2575
2576        for (long organizationId : organizationIds) {
2577            rightOrganizationId = rebuildTree(companyId, organizationId,
2578                    rightOrganizationId);
2579        }
2580
2581        if (parentOrganizationId > 0) {
2582            updateTree.update(parentOrganizationId, leftOrganizationId,
2583                rightOrganizationId);
2584        }
2585
2586        return rightOrganizationId + 1;
2587    }
2588
2589    protected void shrinkTree(Organization organization) {
2590        long companyId = organization.getCompanyId();
2591
2592        long leftOrganizationId = organization.getLeftOrganizationId();
2593        long rightOrganizationId = organization.getRightOrganizationId();
2594
2595        long delta = (rightOrganizationId - leftOrganizationId) + 1;
2596
2597        shrinkTreeLeftOrganizationId.shrink(companyId, rightOrganizationId,
2598            delta);
2599        shrinkTreeRightOrganizationId.shrink(companyId, rightOrganizationId,
2600            delta);
2601
2602        CacheRegistry.clear(OrganizationImpl.class.getName());
2603        EntityCacheUtil.clearCache(OrganizationImpl.class.getName());
2604        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
2605        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
2606    }
2607
2608    public void afterPropertiesSet() {
2609        String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
2610                    com.liferay.portal.util.PropsUtil.get(
2611                        "value.object.listener.com.liferay.portal.model.Organization")));
2612
2613        if (listenerClassNames.length > 0) {
2614            try {
2615                List<ModelListener<Organization>> listenersList = new ArrayList<ModelListener<Organization>>();
2616
2617                for (String listenerClassName : listenerClassNames) {
2618                    listenersList.add((ModelListener<Organization>)Class.forName(
2619                            listenerClassName).newInstance());
2620                }
2621
2622                listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
2623            }
2624            catch (Exception e) {
2625                _log.error(e);
2626            }
2627        }
2628
2629        containsGroup = new ContainsGroup(this);
2630
2631        addGroup = new AddGroup(this);
2632        clearGroups = new ClearGroups(this);
2633        removeGroup = new RemoveGroup(this);
2634
2635        containsUser = new ContainsUser(this);
2636
2637        addUser = new AddUser(this);
2638        clearUsers = new ClearUsers(this);
2639        removeUser = new RemoveUser(this);
2640
2641        expandTreeLeftOrganizationId = new ExpandTreeLeftOrganizationId();
2642        expandTreeRightOrganizationId = new ExpandTreeRightOrganizationId();
2643        shrinkTreeLeftOrganizationId = new ShrinkTreeLeftOrganizationId();
2644        shrinkTreeRightOrganizationId = new ShrinkTreeRightOrganizationId();
2645        updateTree = new UpdateTree();
2646    }
2647
2648    @BeanReference(name = "com.liferay.portal.service.persistence.AccountPersistence.impl")
2649    protected com.liferay.portal.service.persistence.AccountPersistence accountPersistence;
2650    @BeanReference(name = "com.liferay.portal.service.persistence.AddressPersistence.impl")
2651    protected com.liferay.portal.service.persistence.AddressPersistence addressPersistence;
2652    @BeanReference(name = "com.liferay.portal.service.persistence.BrowserTrackerPersistence.impl")
2653    protected com.liferay.portal.service.persistence.BrowserTrackerPersistence browserTrackerPersistence;
2654    @BeanReference(name = "com.liferay.portal.service.persistence.ClassNamePersistence.impl")
2655    protected com.liferay.portal.service.persistence.ClassNamePersistence classNamePersistence;
2656    @BeanReference(name = "com.liferay.portal.service.persistence.CompanyPersistence.impl")
2657    protected com.liferay.portal.service.persistence.CompanyPersistence companyPersistence;
2658    @BeanReference(name = "com.liferay.portal.service.persistence.ContactPersistence.impl")
2659    protected com.liferay.portal.service.persistence.ContactPersistence contactPersistence;
2660    @BeanReference(name = "com.liferay.portal.service.persistence.CountryPersistence.impl")
2661    protected com.liferay.portal.service.persistence.CountryPersistence countryPersistence;
2662    @BeanReference(name = "com.liferay.portal.service.persistence.EmailAddressPersistence.impl")
2663    protected com.liferay.portal.service.persistence.EmailAddressPersistence emailAddressPersistence;
2664    @BeanReference(name = "com.liferay.portal.service.persistence.GroupPersistence.impl")
2665    protected com.liferay.portal.service.persistence.GroupPersistence groupPersistence;
2666    @BeanReference(name = "com.liferay.portal.service.persistence.ImagePersistence.impl")
2667    protected com.liferay.portal.service.persistence.ImagePersistence imagePersistence;
2668    @BeanReference(name = "com.liferay.portal.service.persistence.LayoutPersistence.impl")
2669    protected com.liferay.portal.service.persistence.LayoutPersistence layoutPersistence;
2670    @BeanReference(name = "com.liferay.portal.service.persistence.LayoutSetPersistence.impl")
2671    protected com.liferay.portal.service.persistence.LayoutSetPersistence layoutSetPersistence;
2672    @BeanReference(name = "com.liferay.portal.service.persistence.ListTypePersistence.impl")
2673    protected com.liferay.portal.service.persistence.ListTypePersistence listTypePersistence;
2674    @BeanReference(name = "com.liferay.portal.service.persistence.MembershipRequestPersistence.impl")
2675    protected com.liferay.portal.service.persistence.MembershipRequestPersistence membershipRequestPersistence;
2676    @BeanReference(name = "com.liferay.portal.service.persistence.OrganizationPersistence.impl")
2677    protected com.liferay.portal.service.persistence.OrganizationPersistence organizationPersistence;
2678    @BeanReference(name = "com.liferay.portal.service.persistence.OrgGroupPermissionPersistence.impl")
2679    protected com.liferay.portal.service.persistence.OrgGroupPermissionPersistence orgGroupPermissionPersistence;
2680    @BeanReference(name = "com.liferay.portal.service.persistence.OrgGroupRolePersistence.impl")
2681    protected com.liferay.portal.service.persistence.OrgGroupRolePersistence orgGroupRolePersistence;
2682    @BeanReference(name = "com.liferay.portal.service.persistence.OrgLaborPersistence.impl")
2683    protected com.liferay.portal.service.persistence.OrgLaborPersistence orgLaborPersistence;
2684    @BeanReference(name = "com.liferay.portal.service.persistence.PasswordPolicyPersistence.impl")
2685    protected com.liferay.portal.service.persistence.PasswordPolicyPersistence passwordPolicyPersistence;
2686    @BeanReference(name = "com.liferay.portal.service.persistence.PasswordPolicyRelPersistence.impl")
2687    protected com.liferay.portal.service.persistence.PasswordPolicyRelPersistence passwordPolicyRelPersistence;
2688    @BeanReference(name = "com.liferay.portal.service.persistence.PasswordTrackerPersistence.impl")
2689    protected com.liferay.portal.service.persistence.PasswordTrackerPersistence passwordTrackerPersistence;
2690    @BeanReference(name = "com.liferay.portal.service.persistence.PermissionPersistence.impl")
2691    protected com.liferay.portal.service.persistence.PermissionPersistence permissionPersistence;
2692    @BeanReference(name = "com.liferay.portal.service.persistence.PhonePersistence.impl")
2693    protected com.liferay.portal.service.persistence.PhonePersistence phonePersistence;
2694    @BeanReference(name = "com.liferay.portal.service.persistence.PluginSettingPersistence.impl")
2695    protected com.liferay.portal.service.persistence.PluginSettingPersistence pluginSettingPersistence;
2696    @BeanReference(name = "com.liferay.portal.service.persistence.PortletPersistence.impl")
2697    protected com.liferay.portal.service.persistence.PortletPersistence portletPersistence;
2698    @BeanReference(name = "com.liferay.portal.service.persistence.PortletItemPersistence.impl")
2699    protected com.liferay.portal.service.persistence.PortletItemPersistence portletItemPersistence;
2700    @BeanReference(name = "com.liferay.portal.service.persistence.PortletPreferencesPersistence.impl")
2701    protected com.liferay.portal.service.persistence.PortletPreferencesPersistence portletPreferencesPersistence;
2702    @BeanReference(name = "com.liferay.portal.service.persistence.RegionPersistence.impl")
2703    protected com.liferay.portal.service.persistence.RegionPersistence regionPersistence;
2704    @BeanReference(name = "com.liferay.portal.service.persistence.ReleasePersistence.impl")
2705    protected com.liferay.portal.service.persistence.ReleasePersistence releasePersistence;
2706    @BeanReference(name = "com.liferay.portal.service.persistence.ResourcePersistence.impl")
2707    protected com.liferay.portal.service.persistence.ResourcePersistence resourcePersistence;
2708    @BeanReference(name = "com.liferay.portal.service.persistence.ResourceActionPersistence.impl")
2709    protected com.liferay.portal.service.persistence.ResourceActionPersistence resourceActionPersistence;
2710    @BeanReference(name = "com.liferay.portal.service.persistence.ResourceCodePersistence.impl")
2711    protected com.liferay.portal.service.persistence.ResourceCodePersistence resourceCodePersistence;
2712    @BeanReference(name = "com.liferay.portal.service.persistence.ResourcePermissionPersistence.impl")
2713    protected com.liferay.portal.service.persistence.ResourcePermissionPersistence resourcePermissionPersistence;
2714    @BeanReference(name = "com.liferay.portal.service.persistence.RolePersistence.impl")
2715    protected com.liferay.portal.service.persistence.RolePersistence rolePersistence;
2716    @BeanReference(name = "com.liferay.portal.service.persistence.ServiceComponentPersistence.impl")
2717    protected com.liferay.portal.service.persistence.ServiceComponentPersistence serviceComponentPersistence;
2718    @BeanReference(name = "com.liferay.portal.service.persistence.ShardPersistence.impl")
2719    protected com.liferay.portal.service.persistence.ShardPersistence shardPersistence;
2720    @BeanReference(name = "com.liferay.portal.service.persistence.SubscriptionPersistence.impl")
2721    protected com.liferay.portal.service.persistence.SubscriptionPersistence subscriptionPersistence;
2722    @BeanReference(name = "com.liferay.portal.service.persistence.UserPersistence.impl")
2723    protected com.liferay.portal.service.persistence.UserPersistence userPersistence;
2724    @BeanReference(name = "com.liferay.portal.service.persistence.UserGroupPersistence.impl")
2725    protected com.liferay.portal.service.persistence.UserGroupPersistence userGroupPersistence;
2726    @BeanReference(name = "com.liferay.portal.service.persistence.UserGroupRolePersistence.impl")
2727    protected com.liferay.portal.service.persistence.UserGroupRolePersistence userGroupRolePersistence;
2728    @BeanReference(name = "com.liferay.portal.service.persistence.UserIdMapperPersistence.impl")
2729    protected com.liferay.portal.service.persistence.UserIdMapperPersistence userIdMapperPersistence;
2730    @BeanReference(name = "com.liferay.portal.service.persistence.UserTrackerPersistence.impl")
2731    protected com.liferay.portal.service.persistence.UserTrackerPersistence userTrackerPersistence;
2732    @BeanReference(name = "com.liferay.portal.service.persistence.UserTrackerPathPersistence.impl")
2733    protected com.liferay.portal.service.persistence.UserTrackerPathPersistence userTrackerPathPersistence;
2734    @BeanReference(name = "com.liferay.portal.service.persistence.WebDAVPropsPersistence.impl")
2735    protected com.liferay.portal.service.persistence.WebDAVPropsPersistence webDAVPropsPersistence;
2736    @BeanReference(name = "com.liferay.portal.service.persistence.WebsitePersistence.impl")
2737    protected com.liferay.portal.service.persistence.WebsitePersistence websitePersistence;
2738    protected ContainsGroup containsGroup;
2739    protected AddGroup addGroup;
2740    protected ClearGroups clearGroups;
2741    protected RemoveGroup removeGroup;
2742    protected ContainsUser containsUser;
2743    protected AddUser addUser;
2744    protected ClearUsers clearUsers;
2745    protected RemoveUser removeUser;
2746
2747    protected class ContainsGroup {
2748        protected ContainsGroup(OrganizationPersistenceImpl persistenceImpl) {
2749            super();
2750
2751            _mappingSqlQuery = MappingSqlQueryFactoryUtil.getMappingSqlQuery(getDataSource(),
2752                    _SQL_CONTAINSGROUP,
2753                    new int[] { Types.BIGINT, Types.BIGINT }, RowMapper.COUNT);
2754        }
2755
2756        protected boolean contains(long organizationId, long groupId) {
2757            List<Integer> results = _mappingSqlQuery.execute(new Object[] {
2758                        new Long(organizationId), new Long(groupId)
2759                    });
2760
2761            if (results.size() > 0) {
2762                Integer count = results.get(0);
2763
2764                if (count.intValue() > 0) {
2765                    return true;
2766                }
2767            }
2768
2769            return false;
2770        }
2771
2772        private MappingSqlQuery _mappingSqlQuery;
2773    }
2774
2775    protected class AddGroup {
2776        protected AddGroup(OrganizationPersistenceImpl persistenceImpl) {
2777            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2778                    "INSERT INTO Groups_Orgs (organizationId, groupId) VALUES (?, ?)",
2779                    new int[] { Types.BIGINT, Types.BIGINT });
2780            _persistenceImpl = persistenceImpl;
2781        }
2782
2783        protected void add(long organizationId, long groupId) {
2784            if (!_persistenceImpl.containsGroup.contains(organizationId, groupId)) {
2785                _sqlUpdate.update(new Object[] {
2786                        new Long(organizationId), new Long(groupId)
2787                    });
2788            }
2789        }
2790
2791        private SqlUpdate _sqlUpdate;
2792        private OrganizationPersistenceImpl _persistenceImpl;
2793    }
2794
2795    protected class ClearGroups {
2796        protected ClearGroups(OrganizationPersistenceImpl persistenceImpl) {
2797            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2798                    "DELETE FROM Groups_Orgs WHERE organizationId = ?",
2799                    new int[] { Types.BIGINT });
2800        }
2801
2802        protected void clear(long organizationId) {
2803            _sqlUpdate.update(new Object[] { new Long(organizationId) });
2804        }
2805
2806        private SqlUpdate _sqlUpdate;
2807    }
2808
2809    protected class RemoveGroup {
2810        protected RemoveGroup(OrganizationPersistenceImpl persistenceImpl) {
2811            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2812                    "DELETE FROM Groups_Orgs WHERE organizationId = ? AND groupId = ?",
2813                    new int[] { Types.BIGINT, Types.BIGINT });
2814        }
2815
2816        protected void remove(long organizationId, long groupId) {
2817            _sqlUpdate.update(new Object[] {
2818                    new Long(organizationId), new Long(groupId)
2819                });
2820        }
2821
2822        private SqlUpdate _sqlUpdate;
2823    }
2824
2825    protected class ContainsUser {
2826        protected ContainsUser(OrganizationPersistenceImpl persistenceImpl) {
2827            super();
2828
2829            _mappingSqlQuery = MappingSqlQueryFactoryUtil.getMappingSqlQuery(getDataSource(),
2830                    _SQL_CONTAINSUSER,
2831                    new int[] { Types.BIGINT, Types.BIGINT }, RowMapper.COUNT);
2832        }
2833
2834        protected boolean contains(long organizationId, long userId) {
2835            List<Integer> results = _mappingSqlQuery.execute(new Object[] {
2836                        new Long(organizationId), new Long(userId)
2837                    });
2838
2839            if (results.size() > 0) {
2840                Integer count = results.get(0);
2841
2842                if (count.intValue() > 0) {
2843                    return true;
2844                }
2845            }
2846
2847            return false;
2848        }
2849
2850        private MappingSqlQuery _mappingSqlQuery;
2851    }
2852
2853    protected class AddUser {
2854        protected AddUser(OrganizationPersistenceImpl persistenceImpl) {
2855            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2856                    "INSERT INTO Users_Orgs (organizationId, userId) VALUES (?, ?)",
2857                    new int[] { Types.BIGINT, Types.BIGINT });
2858            _persistenceImpl = persistenceImpl;
2859        }
2860
2861        protected void add(long organizationId, long userId) {
2862            if (!_persistenceImpl.containsUser.contains(organizationId, userId)) {
2863                _sqlUpdate.update(new Object[] {
2864                        new Long(organizationId), new Long(userId)
2865                    });
2866            }
2867        }
2868
2869        private SqlUpdate _sqlUpdate;
2870        private OrganizationPersistenceImpl _persistenceImpl;
2871    }
2872
2873    protected class ClearUsers {
2874        protected ClearUsers(OrganizationPersistenceImpl persistenceImpl) {
2875            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2876                    "DELETE FROM Users_Orgs WHERE organizationId = ?",
2877                    new int[] { Types.BIGINT });
2878        }
2879
2880        protected void clear(long organizationId) {
2881            _sqlUpdate.update(new Object[] { new Long(organizationId) });
2882        }
2883
2884        private SqlUpdate _sqlUpdate;
2885    }
2886
2887    protected class RemoveUser {
2888        protected RemoveUser(OrganizationPersistenceImpl persistenceImpl) {
2889            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2890                    "DELETE FROM Users_Orgs WHERE organizationId = ? AND userId = ?",
2891                    new int[] { Types.BIGINT, Types.BIGINT });
2892        }
2893
2894        protected void remove(long organizationId, long userId) {
2895            _sqlUpdate.update(new Object[] {
2896                    new Long(organizationId), new Long(userId)
2897                });
2898        }
2899
2900        private SqlUpdate _sqlUpdate;
2901    }
2902
2903    protected ExpandTreeLeftOrganizationId expandTreeLeftOrganizationId;
2904    protected ExpandTreeRightOrganizationId expandTreeRightOrganizationId;
2905    protected ShrinkTreeLeftOrganizationId shrinkTreeLeftOrganizationId;
2906    protected ShrinkTreeRightOrganizationId shrinkTreeRightOrganizationId;
2907    protected UpdateTree updateTree;
2908
2909    protected class ExpandTreeLeftOrganizationId {
2910        protected ExpandTreeLeftOrganizationId() {
2911            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2912                    "UPDATE Organization_ SET leftOrganizationId = (leftOrganizationId + 2) WHERE (companyId = ?) AND (leftOrganizationId > ?)",
2913                    new int[] { Types.BIGINT, Types.BIGINT });
2914        }
2915
2916        protected void expand(long companyId, long leftOrganizationId) {
2917            _sqlUpdate.update(new Object[] { companyId, leftOrganizationId });
2918        }
2919
2920        private SqlUpdate _sqlUpdate;
2921    }
2922
2923    protected class ExpandTreeRightOrganizationId {
2924        protected ExpandTreeRightOrganizationId() {
2925            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2926                    "UPDATE Organization_ SET rightOrganizationId = (rightOrganizationId + 2) WHERE (companyId = ?) AND (rightOrganizationId > ?)",
2927                    new int[] { Types.BIGINT, Types.BIGINT });
2928        }
2929
2930        protected void expand(long companyId, long rightOrganizationId) {
2931            _sqlUpdate.update(new Object[] { companyId, rightOrganizationId });
2932        }
2933
2934        private SqlUpdate _sqlUpdate;
2935    }
2936
2937    protected class ShrinkTreeLeftOrganizationId {
2938        protected ShrinkTreeLeftOrganizationId() {
2939            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2940                    "UPDATE Organization_ SET leftOrganizationId = (leftOrganizationId - ?) WHERE (companyId = ?) AND (leftOrganizationId > ?)",
2941                    new int[] { Types.BIGINT, Types.BIGINT, Types.BIGINT });
2942        }
2943
2944        protected void shrink(long companyId, long leftOrganizationId,
2945            long delta) {
2946            _sqlUpdate.update(new Object[] { delta, companyId, leftOrganizationId });
2947        }
2948
2949        private SqlUpdate _sqlUpdate;
2950    }
2951
2952    protected class ShrinkTreeRightOrganizationId {
2953        protected ShrinkTreeRightOrganizationId() {
2954            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2955                    "UPDATE Organization_ SET rightOrganizationId = (rightOrganizationId - ?) WHERE (companyId = ?) AND (rightOrganizationId > ?)",
2956                    new int[] { Types.BIGINT, Types.BIGINT, Types.BIGINT });
2957        }
2958
2959        protected void shrink(long companyId, long rightOrganizationId,
2960            long delta) {
2961            _sqlUpdate.update(new Object[] { delta, companyId, rightOrganizationId });
2962        }
2963
2964        private SqlUpdate _sqlUpdate;
2965    }
2966
2967    protected class UpdateTree {
2968        protected UpdateTree() {
2969            _sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(getDataSource(),
2970                    "UPDATE Organization_ SET leftOrganizationId = ?, rightOrganizationId = ? WHERE organizationId = ?",
2971                    new int[] { Types.BIGINT, Types.BIGINT, Types.BIGINT });
2972        }
2973
2974        protected void update(long organizationId, long leftOrganizationId,
2975            long rightOrganizationId) {
2976            _sqlUpdate.update(new Object[] {
2977                    leftOrganizationId, rightOrganizationId, organizationId
2978                });
2979        }
2980
2981        private SqlUpdate _sqlUpdate;
2982    }
2983
2984    private static final String _SQL_GETGROUPS = "SELECT {Group_.*} FROM Group_ INNER JOIN Groups_Orgs ON (Groups_Orgs.groupId = Group_.groupId) WHERE (Groups_Orgs.organizationId = ?)";
2985    private static final String _SQL_GETGROUPSSIZE = "SELECT COUNT(*) AS COUNT_VALUE FROM Groups_Orgs WHERE organizationId = ?";
2986    private static final String _SQL_CONTAINSGROUP = "SELECT COUNT(*) AS COUNT_VALUE FROM Groups_Orgs WHERE organizationId = ? AND groupId = ?";
2987    private static final String _SQL_GETUSERS = "SELECT {User_.*} FROM User_ INNER JOIN Users_Orgs ON (Users_Orgs.userId = User_.userId) WHERE (Users_Orgs.organizationId = ?)";
2988    private static final String _SQL_GETUSERSSIZE = "SELECT COUNT(*) AS COUNT_VALUE FROM Users_Orgs WHERE organizationId = ?";
2989    private static final String _SQL_CONTAINSUSER = "SELECT COUNT(*) AS COUNT_VALUE FROM Users_Orgs WHERE organizationId = ? AND userId = ?";
2990    private static Log _log = LogFactoryUtil.getLog(OrganizationPersistenceImpl.class);
2991}