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