001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.persistence.impl;
016    
017    import com.liferay.portal.exception.NoSuchModelException;
018    import com.liferay.portal.kernel.configuration.Filter;
019    import com.liferay.portal.kernel.dao.db.DB;
020    import com.liferay.portal.kernel.dao.db.DBManagerUtil;
021    import com.liferay.portal.kernel.dao.db.DBType;
022    import com.liferay.portal.kernel.dao.orm.Dialect;
023    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
024    import com.liferay.portal.kernel.dao.orm.ORMException;
025    import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil;
026    import com.liferay.portal.kernel.dao.orm.Projection;
027    import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
028    import com.liferay.portal.kernel.dao.orm.Session;
029    import com.liferay.portal.kernel.dao.orm.SessionFactory;
030    import com.liferay.portal.kernel.exception.SystemException;
031    import com.liferay.portal.kernel.log.Log;
032    import com.liferay.portal.kernel.log.LogFactoryUtil;
033    import com.liferay.portal.kernel.util.GetterUtil;
034    import com.liferay.portal.kernel.util.NullSafeStringComparator;
035    import com.liferay.portal.kernel.util.OrderByComparator;
036    import com.liferay.portal.kernel.util.PropsKeys;
037    import com.liferay.portal.kernel.util.PropsUtil;
038    import com.liferay.portal.kernel.util.StringBundler;
039    import com.liferay.portal.kernel.util.StringPool;
040    import com.liferay.portal.model.BaseModel;
041    import com.liferay.portal.model.ModelListener;
042    import com.liferay.portal.model.ModelListenerRegistrationUtil;
043    import com.liferay.portal.model.ModelWrapper;
044    import com.liferay.portal.service.ServiceContext;
045    import com.liferay.portal.service.ServiceContextThreadLocal;
046    import com.liferay.portal.service.persistence.BasePersistence;
047    
048    import java.io.Serializable;
049    
050    import java.sql.Connection;
051    import java.sql.Types;
052    
053    import java.util.Collections;
054    import java.util.Comparator;
055    import java.util.List;
056    import java.util.Map;
057    import java.util.Set;
058    
059    import javax.sql.DataSource;
060    
061    /**
062     * The base implementation for all persistence classes. This class should never
063     * need to be used directly.
064     *
065     * <p>
066     * Caching information and settings can be found in
067     * <code>portal.properties</code>
068     * </p>
069     *
070     * @author Brian Wing Shun Chan
071     * @author Shuyang Zhou
072     * @author Peter Fellwock
073     */
074    public class BasePersistenceImpl<T extends BaseModel<T>>
075            implements BasePersistence<T>, SessionFactory {
076    
077            public static final String COUNT_COLUMN_NAME = "COUNT_VALUE";
078    
079            @Override
080            public void clearCache() {
081            }
082    
083            @Override
084            public void clearCache(List<T> model) {
085            }
086    
087            @Override
088            public void clearCache(T model) {
089            }
090    
091            @Override
092            public void closeSession(Session session) {
093                    _sessionFactory.closeSession(session);
094            }
095    
096            @Override
097            public long countWithDynamicQuery(DynamicQuery dynamicQuery) {
098                    return countWithDynamicQuery(
099                            dynamicQuery, ProjectionFactoryUtil.rowCount());
100            }
101    
102            @Override
103            public long countWithDynamicQuery(
104                    DynamicQuery dynamicQuery, Projection projection) {
105    
106                    if (projection == null) {
107                            projection = ProjectionFactoryUtil.rowCount();
108                    }
109    
110                    dynamicQuery.setProjection(projection);
111    
112                    List<Long> results = findWithDynamicQuery(dynamicQuery);
113    
114                    if (results.isEmpty()) {
115                            return 0;
116                    }
117                    else {
118                            return (results.get(0)).longValue();
119                    }
120            }
121    
122            @Override
123            public T fetchByPrimaryKey(Serializable primaryKey) {
124                    throw new UnsupportedOperationException();
125            }
126    
127            @Override
128            public Map<Serializable, T> fetchByPrimaryKeys(
129                    Set<Serializable> primaryKeys) {
130    
131                    throw new UnsupportedOperationException();
132            }
133    
134            @Override
135            @SuppressWarnings("unused")
136            public T findByPrimaryKey(Serializable primaryKey)
137                    throws NoSuchModelException {
138    
139                    throw new UnsupportedOperationException();
140            }
141    
142            @Override
143            public <V> List<V> findWithDynamicQuery(DynamicQuery dynamicQuery) {
144                    Session session = null;
145    
146                    try {
147                            session = openSession();
148    
149                            dynamicQuery.compile(session);
150    
151                            return dynamicQuery.list();
152                    }
153                    catch (Exception e) {
154                            throw processException(e);
155                    }
156                    finally {
157                            closeSession(session);
158                    }
159            }
160    
161            @Override
162            public <V> List<V> findWithDynamicQuery(
163                    DynamicQuery dynamicQuery, int start, int end) {
164    
165                    Session session = null;
166    
167                    try {
168                            session = openSession();
169    
170                            dynamicQuery.setLimit(start, end);
171    
172                            dynamicQuery.compile(session);
173    
174                            return dynamicQuery.list();
175                    }
176                    catch (Exception e) {
177                            throw processException(e);
178                    }
179                    finally {
180                            closeSession(session);
181                    }
182            }
183    
184            @Override
185            public <V> List<V> findWithDynamicQuery(
186                    DynamicQuery dynamicQuery, int start, int end,
187                    OrderByComparator<V> orderByComparator) {
188    
189                    OrderFactoryUtil.addOrderByComparator(dynamicQuery, orderByComparator);
190    
191                    return findWithDynamicQuery(dynamicQuery, start, end);
192            }
193    
194            @Override
195            public void flush() {
196                    try {
197                            Session session = _sessionFactory.getCurrentSession();
198    
199                            if (session != null) {
200                                    session.flush();
201                            }
202                    }
203                    catch (Exception e) {
204                            throw processException(e);
205                    }
206            }
207    
208            @Override
209            public Set<String> getBadColumnNames() {
210                    return Collections.emptySet();
211            }
212    
213            @Override
214            public Session getCurrentSession() throws ORMException {
215                    return _sessionFactory.getCurrentSession();
216            }
217    
218            @Override
219            public DataSource getDataSource() {
220                    return _dataSource;
221            }
222    
223            public DB getDB() {
224                    return _db;
225            }
226    
227            @Override
228            public Dialect getDialect() {
229                    return _dialect;
230            }
231    
232            @Override
233            public ModelListener<T>[] getListeners() {
234                    return ModelListenerRegistrationUtil.getModelListeners(getModelClass());
235            }
236    
237            @Override
238            public Class<T> getModelClass() {
239                    return _modelClass;
240            }
241    
242            @Override
243            public Session openNewSession(Connection connection) throws ORMException {
244                    return _sessionFactory.openNewSession(connection);
245            }
246    
247            @Override
248            public Session openSession() throws ORMException {
249                    return _sessionFactory.openSession();
250            }
251    
252            @Override
253            public SystemException processException(Exception e) {
254                    if (!(e instanceof ORMException)) {
255                            _log.error("Caught unexpected exception " + e.getClass().getName());
256                    }
257    
258                    if (_log.isDebugEnabled()) {
259                            _log.debug(e, e);
260                    }
261    
262                    return new SystemException(e);
263            }
264    
265            @Override
266            public void registerListener(ModelListener<T> listener) {
267                    ModelListenerRegistrationUtil.register(listener);
268            }
269    
270            @Override
271            @SuppressWarnings("unused")
272            public T remove(Serializable primaryKey) throws NoSuchModelException {
273                    throw new UnsupportedOperationException();
274            }
275    
276            @Override
277            public T remove(T model) {
278                    if (model instanceof ModelWrapper) {
279                            ModelWrapper<T> modelWrapper = (ModelWrapper<T>)model;
280    
281                            model = modelWrapper.getWrappedModel();
282                    }
283    
284                    ModelListener<T>[] listeners = getListeners();
285    
286                    for (ModelListener<T> listener : listeners) {
287                            listener.onBeforeRemove(model);
288                    }
289    
290                    model = removeImpl(model);
291    
292                    for (ModelListener<T> listener : listeners) {
293                            listener.onAfterRemove(model);
294                    }
295    
296                    return model;
297            }
298    
299            @Override
300            public void setDataSource(DataSource dataSource) {
301                    _dataSource = dataSource;
302            }
303    
304            public void setSessionFactory(SessionFactory sessionFactory) {
305                    _sessionFactory = sessionFactory;
306                    _dialect = _sessionFactory.getDialect();
307                    _db = DBManagerUtil.getDB(_dialect, getDataSource());
308    
309                    DBType dbType = _db.getDBType();
310    
311                    _databaseOrderByMaxColumns = GetterUtil.getInteger(
312                            PropsUtil.get(
313                                    PropsKeys.DATABASE_ORDER_BY_MAX_COLUMNS,
314                                    new Filter(dbType.getName())));
315            }
316    
317            @Override
318            public void unregisterListener(ModelListener<T> listener) {
319                    ModelListenerRegistrationUtil.unregister(listener);
320            }
321    
322            @Override
323            public T update(T model) {
324                    if (model instanceof ModelWrapper) {
325                            ModelWrapper<T> modelWrapper = (ModelWrapper<T>)model;
326    
327                            model = modelWrapper.getWrappedModel();
328                    }
329    
330                    boolean isNew = model.isNew();
331    
332                    ModelListener<T>[] listeners = getListeners();
333    
334                    for (ModelListener<T> listener : listeners) {
335                            if (isNew) {
336                                    listener.onBeforeCreate(model);
337                            }
338                            else {
339                                    listener.onBeforeUpdate(model);
340                            }
341                    }
342    
343                    model = updateImpl(model);
344    
345                    for (ModelListener<T> listener : listeners) {
346                            if (isNew) {
347                                    listener.onAfterCreate(model);
348                            }
349                            else {
350                                    listener.onAfterUpdate(model);
351                            }
352                    }
353    
354                    return model;
355            }
356    
357            /**
358             * @deprecated As of 6.2.0, replaced by {@link #update(BaseModel)}}
359             */
360            @Deprecated
361            @Override
362            public T update(T model, boolean merge) {
363                    if (model instanceof ModelWrapper) {
364                            ModelWrapper<T> modelWrapper = (ModelWrapper<T>)model;
365    
366                            model = modelWrapper.getWrappedModel();
367                    }
368    
369                    boolean isNew = model.isNew();
370    
371                    ModelListener<T>[] listeners = getListeners();
372    
373                    for (ModelListener<T> listener : listeners) {
374                            if (isNew) {
375                                    listener.onBeforeCreate(model);
376                            }
377                            else {
378                                    listener.onBeforeUpdate(model);
379                            }
380                    }
381    
382                    model = updateImpl(model, merge);
383    
384                    for (ModelListener<T> listener : listeners) {
385                            if (isNew) {
386                                    listener.onAfterCreate(model);
387                            }
388                            else {
389                                    listener.onAfterUpdate(model);
390                            }
391                    }
392    
393                    return model;
394            }
395    
396            /**
397             * @deprecated As of 6.2.0, replaced by {@link #update(BaseModel,
398             *             ServiceContext)}}
399             */
400            @Deprecated
401            @Override
402            public T update(T model, boolean merge, ServiceContext serviceContext) {
403                    return update(model, serviceContext);
404            }
405    
406            @Override
407            public T update(T model, ServiceContext serviceContext) {
408                    try {
409                            ServiceContextThreadLocal.pushServiceContext(serviceContext);
410    
411                            update(model);
412    
413                            return model;
414                    }
415                    finally {
416                            ServiceContextThreadLocal.popServiceContext();
417                    }
418            }
419    
420            protected static String removeConjunction(String sql) {
421                    int pos = sql.indexOf(" AND ");
422    
423                    if (pos != -1) {
424                            sql = sql.substring(0, pos);
425                    }
426    
427                    return sql;
428            }
429    
430            protected void appendOrderByComparator(
431                    StringBundler query, String entityAlias,
432                    OrderByComparator<T> orderByComparator) {
433    
434                    appendOrderByComparator(query, entityAlias, orderByComparator, false);
435            }
436    
437            protected void appendOrderByComparator(
438                    StringBundler query, String entityAlias,
439                    OrderByComparator<T> orderByComparator, boolean sqlQuery) {
440    
441                    query.append(ORDER_BY_CLAUSE);
442    
443                    String[] orderByFields = orderByComparator.getOrderByFields();
444    
445                    int length = orderByFields.length;
446    
447                    if ((_databaseOrderByMaxColumns > 0) &&
448                            (_databaseOrderByMaxColumns < length)) {
449    
450                            length = _databaseOrderByMaxColumns;
451                    }
452    
453                    for (int i = 0; i < length; i++) {
454                            query.append(
455                                    getColumnName(entityAlias, orderByFields[i], sqlQuery));
456    
457                            if ((i + 1) < length) {
458                                    if (orderByComparator.isAscending(orderByFields[i])) {
459                                            query.append(ORDER_BY_ASC_HAS_NEXT);
460                                    }
461                                    else {
462                                            query.append(ORDER_BY_DESC_HAS_NEXT);
463                                    }
464                            }
465                            else {
466                                    if (orderByComparator.isAscending(orderByFields[i])) {
467                                            query.append(ORDER_BY_ASC);
468                                    }
469                                    else {
470                                            query.append(ORDER_BY_DESC);
471                                    }
472                            }
473                    }
474            }
475    
476            protected ClassLoader getClassLoader() {
477                    Class<?> clazz = getClass();
478    
479                    return clazz.getClassLoader();
480            }
481    
482            protected String getColumnName(
483                    String entityAlias, String fieldName, boolean sqlQuery) {
484    
485                    String columnName = fieldName;
486    
487                    Set<String> badColumnNames = getBadColumnNames();
488    
489                    if (badColumnNames.contains(fieldName)) {
490                            columnName = columnName.concat(StringPool.UNDERLINE);
491                    }
492    
493                    if (sqlQuery) {
494                            fieldName = columnName;
495                    }
496    
497                    fieldName = entityAlias.concat(fieldName);
498    
499                    Map<String, Integer> tableColumnsMap = getTableColumnsMap();
500    
501                    Integer type = tableColumnsMap.get(columnName);
502    
503                    if (type == null) {
504                            throw new IllegalArgumentException(
505                                    "Unknown column name " + columnName);
506                    }
507    
508                    if (type == Types.CLOB) {
509                            fieldName = CAST_CLOB_TEXT_OPEN.concat(fieldName).concat(
510                                    StringPool.CLOSE_PARENTHESIS);
511                    }
512    
513                    return fieldName;
514            }
515    
516            protected Map<String, Integer> getTableColumnsMap() {
517                    throw new UnsupportedOperationException();
518            }
519    
520            /**
521             * Removes the model instance from the database. {@link #update(BaseModel,
522             * boolean)} depends on this method to implement the remove operation; it
523             * only notifies the model listeners.
524             *
525             * @param  model the model instance to remove
526             * @return the model instance that was removed
527             */
528            protected T removeImpl(T model) {
529                    throw new UnsupportedOperationException();
530            }
531    
532            protected void setModelClass(Class<T> modelClass) {
533                    _modelClass = modelClass;
534            }
535    
536            /**
537             * Updates the model instance in the database or adds it if it does not yet
538             * exist. {@link #remove(BaseModel)} depends on this method to implement the
539             * update operation; it only notifies the model listeners.
540             *
541             * @param  model the model instance to update
542             * @return the model instance that was updated
543             */
544            protected T updateImpl(T model) {
545                    throw new UnsupportedOperationException();
546            }
547    
548            /**
549             * @deprecated As of 6.2.0, replaced by {@link #updateImpl(BaseModel)}
550             */
551            @Deprecated
552            protected T updateImpl(T model, boolean merge) {
553                    return updateImpl(model);
554            }
555    
556            protected static final String CAST_CLOB_TEXT_OPEN = "CAST_CLOB_TEXT(";
557    
558            protected static final Object[] FINDER_ARGS_EMPTY = new Object[0];
559    
560            protected static final Comparator<String> NULL_SAFE_STRING_COMPARATOR =
561                    new NullSafeStringComparator();
562    
563            protected static final String ORDER_BY_ASC = " ASC";
564    
565            protected static final String ORDER_BY_ASC_HAS_NEXT = " ASC, ";
566    
567            protected static final String ORDER_BY_CLAUSE = " ORDER BY ";
568    
569            protected static final String ORDER_BY_DESC = " DESC";
570    
571            protected static final String ORDER_BY_DESC_HAS_NEXT = " DESC, ";
572    
573            protected static final String WHERE_AND = " AND ";
574    
575            protected static final String WHERE_GREATER_THAN = " >= ? ";
576    
577            protected static final String WHERE_GREATER_THAN_HAS_NEXT = " >= ? AND ";
578    
579            protected static final String WHERE_LESSER_THAN = " <= ? ";
580    
581            protected static final String WHERE_LESSER_THAN_HAS_NEXT = " <= ? AND ";
582    
583            protected static final String WHERE_OR = " OR ";
584    
585            /**
586             * @deprecated As of 7.0.0, with no direct replacement
587             */
588            @Deprecated
589            protected ModelListener<T>[] listeners = new ModelListener[0];
590    
591            private static final Log _log = LogFactoryUtil.getLog(
592                    BasePersistenceImpl.class);
593    
594            private int _databaseOrderByMaxColumns;
595            private DataSource _dataSource;
596            private DB _db;
597            private Dialect _dialect;
598            private Class<T> _modelClass;
599            private SessionFactory _sessionFactory;
600    
601    }