package br.mp.mprj.portal.portlet.gestaomensagens.service.service.persistence;

import br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.Mensagem;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemImpl;
import br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl;
import br.mp.mprj.portal.portlet.gestaomensagens.service.service.persistence.MensagemPersistence;

import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.SetUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.UnmodifiableList;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * The persistence implementation for the mensagem service.
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Henrique Simoes
 * @see MensagemPersistence
 * @see MensagemUtil
 * @generated
 */
public class MensagemPersistenceImpl extends BasePersistenceImpl<Mensagem>
    implements MensagemPersistence {
    /*
     * NOTE FOR DEVELOPERS:
     *
     * Never modify or reference this class directly. Always use {@link MensagemUtil} to access the mensagem persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
     */
    public static final String FINDER_CLASS_NAME_ENTITY = MensagemImpl.class.getName();
    public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
        ".List1";
    public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
        ".List2";
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByUuid",
            new String[] {
                String.class.getName(),
                
            Integer.class.getName(), Integer.class.getName(),
                OrderByComparator.class.getName()
            });
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid",
            new String[] { String.class.getName() },
            MensagemModelImpl.UUID_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_UUID = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid",
            new String[] { String.class.getName() });
    private static final String _FINDER_COLUMN_UUID_UUID_1 = "mensagem.uuid IS NULL";
    private static final String _FINDER_COLUMN_UUID_UUID_2 = "mensagem.uuid = ?";
    private static final String _FINDER_COLUMN_UUID_UUID_3 = "(mensagem.uuid IS NULL OR mensagem.uuid = '')";
    public static final FinderPath FINDER_PATH_FETCH_BY_UUID_G = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_ENTITY, "fetchByUUID_G",
            new String[] { String.class.getName(), Long.class.getName() },
            MensagemModelImpl.UUID_COLUMN_BITMASK |
            MensagemModelImpl.GROUPID_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_UUID_G = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUUID_G",
            new String[] { String.class.getName(), Long.class.getName() });
    private static final String _FINDER_COLUMN_UUID_G_UUID_1 = "mensagem.uuid IS NULL AND ";
    private static final String _FINDER_COLUMN_UUID_G_UUID_2 = "mensagem.uuid = ? AND ";
    private static final String _FINDER_COLUMN_UUID_G_UUID_3 = "(mensagem.uuid IS NULL OR mensagem.uuid = '') AND ";
    private static final String _FINDER_COLUMN_UUID_G_GROUPID_2 = "mensagem.groupId = ?";
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByUuid_C",
            new String[] {
                String.class.getName(), Long.class.getName(),
                
            Integer.class.getName(), Integer.class.getName(),
                OrderByComparator.class.getName()
            });
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C =
        new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid_C",
            new String[] { String.class.getName(), Long.class.getName() },
            MensagemModelImpl.UUID_COLUMN_BITMASK |
            MensagemModelImpl.COMPANYID_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_UUID_C = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid_C",
            new String[] { String.class.getName(), Long.class.getName() });
    private static final String _FINDER_COLUMN_UUID_C_UUID_1 = "mensagem.uuid IS NULL AND ";
    private static final String _FINDER_COLUMN_UUID_C_UUID_2 = "mensagem.uuid = ? AND ";
    private static final String _FINDER_COLUMN_UUID_C_UUID_3 = "(mensagem.uuid IS NULL OR mensagem.uuid = '') AND ";
    private static final String _FINDER_COLUMN_UUID_C_COMPANYID_2 = "mensagem.companyId = ?";
    public static final FinderPath FINDER_PATH_FETCH_BY_CODIGO = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_ENTITY, "fetchByCodigo",
            new String[] { String.class.getName() },
            MensagemModelImpl.CODIGOMENSAGEM_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_CODIGO = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByCodigo",
            new String[] { String.class.getName() });
    private static final String _FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_1 = "mensagem.codigoMensagem IS NULL";
    private static final String _FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_2 = "mensagem.codigoMensagem = ?";
    private static final String _FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_3 = "(mensagem.codigoMensagem IS NULL OR mensagem.codigoMensagem = '')";
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_GROUPID = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByGroupId",
            new String[] {
                Long.class.getName(),
                
            Integer.class.getName(), Integer.class.getName(),
                OrderByComparator.class.getName()
            });
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUPID =
        new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByGroupId",
            new String[] { Long.class.getName() },
            MensagemModelImpl.GROUPID_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_GROUPID = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByGroupId",
            new String[] { Long.class.getName() });
    private static final String _FINDER_COLUMN_GROUPID_GROUPID_2 = "mensagem.groupId = ?";
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_STATUSWORKFLOW =
        new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByStatusWorkflow",
            new String[] {
                Integer.class.getName(),
                
            Integer.class.getName(), Integer.class.getName(),
                OrderByComparator.class.getName()
            });
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_STATUSWORKFLOW =
        new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByStatusWorkflow",
            new String[] { Integer.class.getName() },
            MensagemModelImpl.STATUSWORKFLOW_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_STATUSWORKFLOW = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByStatusWorkflow",
            new String[] { Integer.class.getName() });
    private static final String _FINDER_COLUMN_STATUSWORKFLOW_STATUSWORKFLOW_2 = "mensagem.statusWorkflow = ?";
    public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_USERIDCRIADOR =
        new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByUserIdCriador",
            new String[] {
                Long.class.getName(),
                
            Integer.class.getName(), Integer.class.getName(),
                OrderByComparator.class.getName()
            });
    public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_USERIDCRIADOR =
        new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUserIdCriador",
            new String[] { Long.class.getName() },
            MensagemModelImpl.USERIDCRIADOR_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_USERIDCRIADOR = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUserIdCriador",
            new String[] { Long.class.getName() });
    private static final String _FINDER_COLUMN_USERIDCRIADOR_USERIDCRIADOR_2 = "mensagem.userIdCriador = ?";
    public static final FinderPath FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, MensagemImpl.class,
            FINDER_CLASS_NAME_ENTITY, "fetchByRascunhoCriador",
            new String[] { Boolean.class.getName(), Long.class.getName() },
            MensagemModelImpl.RASCUNHO_COLUMN_BITMASK |
            MensagemModelImpl.USERIDCRIADOR_COLUMN_BITMASK);
    public static final FinderPath FINDER_PATH_COUNT_BY_RASCUNHOCRIADOR = new FinderPath(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemModelImpl.FINDER_CACHE_ENABLED, Long.class,
            FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
            "countByRascunhoCriador",
            new String[] { Boolean.class.getName(), Long.class.getName() });
    private static final String _FINDER_COLUMN_RASCUNHOCRIADOR_RASCUNHO_2 = "mensagem.rascunho = ? AND ";
    private static final String _FINDER_COLUMN_RASCUNHOCRIADOR_USERIDCRIADOR_2 = "mensagem.userIdCriador = ?";
    private static final String _SQL_SELECT_MENSAGEM = "SELECT mensagem FROM Mensagem mensagem";
    private static final String _SQL_SELECT_MENSAGEM_WHERE = "SELECT mensagem FROM Mensagem mensagem WHERE ";
    private static final String _SQL_COUNT_MENSAGEM = "SELECT COUNT(mensagem) FROM Mensagem mensagem";
    private static final String _SQL_COUNT_MENSAGEM_WHERE = "SELECT COUNT(mensagem) FROM Mensagem mensagem WHERE ";
    private static final String _ORDER_BY_ENTITY_ALIAS = "mensagem.";
    private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Mensagem exists with the primary key ";
    private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Mensagem exists with the key {";
    private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get(
                PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE));
    private static Log _log = LogFactoryUtil.getLog(MensagemPersistenceImpl.class);
    private static Set<String> _badColumnNames = SetUtil.fromArray(new String[] {
                "uuid"
            });
    private static Mensagem _nullMensagem = new MensagemImpl() {
            @Override
            public Object clone() {
                return this;
            }

            @Override
            public CacheModel<Mensagem> toCacheModel() {
                return _nullMensagemCacheModel;
            }
        };

    private static CacheModel<Mensagem> _nullMensagemCacheModel = new CacheModel<Mensagem>() {
            @Override
            public Mensagem toEntityModel() {
                return _nullMensagem;
            }
        };

    public MensagemPersistenceImpl() {
        setModelClass(Mensagem.class);
    }

    /**
     * Returns all the mensagems where uuid = &#63;.
     *
     * @param uuid the uuid
     * @return the matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUuid(String uuid) throws SystemException {
        return findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the mensagems where uuid = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param uuid the uuid
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @return the range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUuid(String uuid, int start, int end)
        throws SystemException {
        return findByUuid(uuid, start, end, null);
    }

    /**
     * Returns an ordered range of all the mensagems where uuid = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param uuid the uuid
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUuid(String uuid, int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID;
            finderArgs = new Object[] { uuid };
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID;
            finderArgs = new Object[] { uuid, start, end, orderByComparator };
        }

        List<Mensagem> list = (List<Mensagem>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if ((list != null) && !list.isEmpty()) {
            for (Mensagem mensagem : list) {
                if (!Validator.equals(uuid, mensagem.getUuid())) {
                    list = null;

                    break;
                }
            }
        }

        if (list == null) {
            StringBundler query = null;

            if (orderByComparator != null) {
                query = new StringBundler(3 +
                        (orderByComparator.getOrderByFields().length * 3));
            } else {
                query = new StringBundler(3);
            }

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            boolean bindUuid = false;

            if (uuid == null) {
                query.append(_FINDER_COLUMN_UUID_UUID_1);
            } else if (uuid.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_UUID_UUID_3);
            } else {
                bindUuid = true;

                query.append(_FINDER_COLUMN_UUID_UUID_2);
            }

            if (orderByComparator != null) {
                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);
            } else
             if (pagination) {
                query.append(MensagemModelImpl.ORDER_BY_JPQL);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindUuid) {
                    qPos.add(uuid);
                }

                if (!pagination) {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<Mensagem>(list);
                } else {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Returns the first mensagem in the ordered set where uuid = &#63;.
     *
     * @param uuid the uuid
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUuid_First(String uuid,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUuid_First(uuid, orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("uuid=");
        msg.append(uuid);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the first mensagem in the ordered set where uuid = &#63;.
     *
     * @param uuid the uuid
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUuid_First(String uuid,
        OrderByComparator orderByComparator) throws SystemException {
        List<Mensagem> list = findByUuid(uuid, 0, 1, orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the last mensagem in the ordered set where uuid = &#63;.
     *
     * @param uuid the uuid
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUuid_Last(String uuid,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUuid_Last(uuid, orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("uuid=");
        msg.append(uuid);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the last mensagem in the ordered set where uuid = &#63;.
     *
     * @param uuid the uuid
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUuid_Last(String uuid,
        OrderByComparator orderByComparator) throws SystemException {
        int count = countByUuid(uuid);

        if (count == 0) {
            return null;
        }

        List<Mensagem> list = findByUuid(uuid, count - 1, count,
                orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the mensagems before and after the current mensagem in the ordered set where uuid = &#63;.
     *
     * @param mensagemId the primary key of the current mensagem
     * @param uuid the uuid
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the previous, current, and next mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem[] findByUuid_PrevAndNext(long mensagemId, String uuid,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByPrimaryKey(mensagemId);

        Session session = null;

        try {
            session = openSession();

            Mensagem[] array = new MensagemImpl[3];

            array[0] = getByUuid_PrevAndNext(session, mensagem, uuid,
                    orderByComparator, true);

            array[1] = mensagem;

            array[2] = getByUuid_PrevAndNext(session, mensagem, uuid,
                    orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected Mensagem getByUuid_PrevAndNext(Session session,
        Mensagem mensagem, String uuid, OrderByComparator orderByComparator,
        boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_MENSAGEM_WHERE);

        boolean bindUuid = false;

        if (uuid == null) {
            query.append(_FINDER_COLUMN_UUID_UUID_1);
        } else if (uuid.equals(StringPool.BLANK)) {
            query.append(_FINDER_COLUMN_UUID_UUID_3);
        } else {
            bindUuid = true;

            query.append(_FINDER_COLUMN_UUID_UUID_2);
        }

        if (orderByComparator != null) {
            String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

            if (orderByConditionFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByConditionFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByConditionFields[i]);

                if ((i + 1) < orderByConditionFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            String[] orderByFields = orderByComparator.getOrderByFields();

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        } else {
            query.append(MensagemModelImpl.ORDER_BY_JPQL);
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        if (bindUuid) {
            qPos.add(uuid);
        }

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByConditionValues(mensagem);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<Mensagem> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    /**
     * Removes all the mensagems where uuid = &#63; from the database.
     *
     * @param uuid the uuid
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeByUuid(String uuid) throws SystemException {
        for (Mensagem mensagem : findByUuid(uuid, QueryUtil.ALL_POS,
                QueryUtil.ALL_POS, null)) {
            remove(mensagem);
        }
    }

    /**
     * Returns the number of mensagems where uuid = &#63;.
     *
     * @param uuid the uuid
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByUuid(String uuid) throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID;

        Object[] finderArgs = new Object[] { uuid };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(2);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            boolean bindUuid = false;

            if (uuid == null) {
                query.append(_FINDER_COLUMN_UUID_UUID_1);
            } else if (uuid.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_UUID_UUID_3);
            } else {
                bindUuid = true;

                query.append(_FINDER_COLUMN_UUID_UUID_2);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindUuid) {
                    qPos.add(uuid);
                }

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns the mensagem where uuid = &#63; and groupId = &#63; or throws a {@link br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException} if it could not be found.
     *
     * @param uuid the uuid
     * @param groupId the group ID
     * @return the matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUUID_G(String uuid, long groupId)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUUID_G(uuid, groupId);

        if (mensagem == null) {
            StringBundler msg = new StringBundler(6);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("uuid=");
            msg.append(uuid);

            msg.append(", groupId=");
            msg.append(groupId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            if (_log.isWarnEnabled()) {
                _log.warn(msg.toString());
            }

            throw new NoSuchMensagemException(msg.toString());
        }

        return mensagem;
    }

    /**
     * Returns the mensagem where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
     *
     * @param uuid the uuid
     * @param groupId the group ID
     * @return the matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUUID_G(String uuid, long groupId)
        throws SystemException {
        return fetchByUUID_G(uuid, groupId, true);
    }

    /**
     * Returns the mensagem where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
     *
     * @param uuid the uuid
     * @param groupId the group ID
     * @param retrieveFromCache whether to use the finder cache
     * @return the matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUUID_G(String uuid, long groupId,
        boolean retrieveFromCache) throws SystemException {
        Object[] finderArgs = new Object[] { uuid, groupId };

        Object result = null;

        if (retrieveFromCache) {
            result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_UUID_G,
                    finderArgs, this);
        }

        if (result instanceof Mensagem) {
            Mensagem mensagem = (Mensagem) result;

            if (!Validator.equals(uuid, mensagem.getUuid()) ||
                    (groupId != mensagem.getGroupId())) {
                result = null;
            }
        }

        if (result == null) {
            StringBundler query = new StringBundler(4);

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            boolean bindUuid = false;

            if (uuid == null) {
                query.append(_FINDER_COLUMN_UUID_G_UUID_1);
            } else if (uuid.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_UUID_G_UUID_3);
            } else {
                bindUuid = true;

                query.append(_FINDER_COLUMN_UUID_G_UUID_2);
            }

            query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindUuid) {
                    qPos.add(uuid);
                }

                qPos.add(groupId);

                List<Mensagem> list = q.list();

                if (list.isEmpty()) {
                    FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_G,
                        finderArgs, list);
                } else {
                    Mensagem mensagem = list.get(0);

                    result = mensagem;

                    cacheResult(mensagem);

                    if ((mensagem.getUuid() == null) ||
                            !mensagem.getUuid().equals(uuid) ||
                            (mensagem.getGroupId() != groupId)) {
                        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_G,
                            finderArgs, mensagem);
                    }
                }
            } catch (Exception e) {
                FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_UUID_G,
                    finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        if (result instanceof List<?>) {
            return null;
        } else {
            return (Mensagem) result;
        }
    }

    /**
     * Removes the mensagem where uuid = &#63; and groupId = &#63; from the database.
     *
     * @param uuid the uuid
     * @param groupId the group ID
     * @return the mensagem that was removed
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem removeByUUID_G(String uuid, long groupId)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByUUID_G(uuid, groupId);

        return remove(mensagem);
    }

    /**
     * Returns the number of mensagems where uuid = &#63; and groupId = &#63;.
     *
     * @param uuid the uuid
     * @param groupId the group ID
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByUUID_G(String uuid, long groupId)
        throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_G;

        Object[] finderArgs = new Object[] { uuid, groupId };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(3);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            boolean bindUuid = false;

            if (uuid == null) {
                query.append(_FINDER_COLUMN_UUID_G_UUID_1);
            } else if (uuid.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_UUID_G_UUID_3);
            } else {
                bindUuid = true;

                query.append(_FINDER_COLUMN_UUID_G_UUID_2);
            }

            query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindUuid) {
                    qPos.add(uuid);
                }

                qPos.add(groupId);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns all the mensagems where uuid = &#63; and companyId = &#63;.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @return the matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUuid_C(String uuid, long companyId)
        throws SystemException {
        return findByUuid_C(uuid, companyId, QueryUtil.ALL_POS,
            QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the mensagems where uuid = &#63; and companyId = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @return the range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUuid_C(String uuid, long companyId, int start,
        int end) throws SystemException {
        return findByUuid_C(uuid, companyId, start, end, null);
    }

    /**
     * Returns an ordered range of all the mensagems where uuid = &#63; and companyId = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUuid_C(String uuid, long companyId, int start,
        int end, OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C;
            finderArgs = new Object[] { uuid, companyId };
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C;
            finderArgs = new Object[] {
                    uuid, companyId,
                    
                    start, end, orderByComparator
                };
        }

        List<Mensagem> list = (List<Mensagem>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if ((list != null) && !list.isEmpty()) {
            for (Mensagem mensagem : list) {
                if (!Validator.equals(uuid, mensagem.getUuid()) ||
                        (companyId != mensagem.getCompanyId())) {
                    list = null;

                    break;
                }
            }
        }

        if (list == null) {
            StringBundler query = null;

            if (orderByComparator != null) {
                query = new StringBundler(4 +
                        (orderByComparator.getOrderByFields().length * 3));
            } else {
                query = new StringBundler(4);
            }

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            boolean bindUuid = false;

            if (uuid == null) {
                query.append(_FINDER_COLUMN_UUID_C_UUID_1);
            } else if (uuid.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_UUID_C_UUID_3);
            } else {
                bindUuid = true;

                query.append(_FINDER_COLUMN_UUID_C_UUID_2);
            }

            query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);

            if (orderByComparator != null) {
                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);
            } else
             if (pagination) {
                query.append(MensagemModelImpl.ORDER_BY_JPQL);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindUuid) {
                    qPos.add(uuid);
                }

                qPos.add(companyId);

                if (!pagination) {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<Mensagem>(list);
                } else {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Returns the first mensagem in the ordered set where uuid = &#63; and companyId = &#63;.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUuid_C_First(String uuid, long companyId,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUuid_C_First(uuid, companyId,
                orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(6);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("uuid=");
        msg.append(uuid);

        msg.append(", companyId=");
        msg.append(companyId);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the first mensagem in the ordered set where uuid = &#63; and companyId = &#63;.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUuid_C_First(String uuid, long companyId,
        OrderByComparator orderByComparator) throws SystemException {
        List<Mensagem> list = findByUuid_C(uuid, companyId, 0, 1,
                orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the last mensagem in the ordered set where uuid = &#63; and companyId = &#63;.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUuid_C_Last(String uuid, long companyId,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUuid_C_Last(uuid, companyId,
                orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(6);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("uuid=");
        msg.append(uuid);

        msg.append(", companyId=");
        msg.append(companyId);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the last mensagem in the ordered set where uuid = &#63; and companyId = &#63;.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUuid_C_Last(String uuid, long companyId,
        OrderByComparator orderByComparator) throws SystemException {
        int count = countByUuid_C(uuid, companyId);

        if (count == 0) {
            return null;
        }

        List<Mensagem> list = findByUuid_C(uuid, companyId, count - 1, count,
                orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the mensagems before and after the current mensagem in the ordered set where uuid = &#63; and companyId = &#63;.
     *
     * @param mensagemId the primary key of the current mensagem
     * @param uuid the uuid
     * @param companyId the company ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the previous, current, and next mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem[] findByUuid_C_PrevAndNext(long mensagemId, String uuid,
        long companyId, OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByPrimaryKey(mensagemId);

        Session session = null;

        try {
            session = openSession();

            Mensagem[] array = new MensagemImpl[3];

            array[0] = getByUuid_C_PrevAndNext(session, mensagem, uuid,
                    companyId, orderByComparator, true);

            array[1] = mensagem;

            array[2] = getByUuid_C_PrevAndNext(session, mensagem, uuid,
                    companyId, orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected Mensagem getByUuid_C_PrevAndNext(Session session,
        Mensagem mensagem, String uuid, long companyId,
        OrderByComparator orderByComparator, boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_MENSAGEM_WHERE);

        boolean bindUuid = false;

        if (uuid == null) {
            query.append(_FINDER_COLUMN_UUID_C_UUID_1);
        } else if (uuid.equals(StringPool.BLANK)) {
            query.append(_FINDER_COLUMN_UUID_C_UUID_3);
        } else {
            bindUuid = true;

            query.append(_FINDER_COLUMN_UUID_C_UUID_2);
        }

        query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);

        if (orderByComparator != null) {
            String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

            if (orderByConditionFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByConditionFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByConditionFields[i]);

                if ((i + 1) < orderByConditionFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            String[] orderByFields = orderByComparator.getOrderByFields();

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        } else {
            query.append(MensagemModelImpl.ORDER_BY_JPQL);
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        if (bindUuid) {
            qPos.add(uuid);
        }

        qPos.add(companyId);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByConditionValues(mensagem);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<Mensagem> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    /**
     * Removes all the mensagems where uuid = &#63; and companyId = &#63; from the database.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeByUuid_C(String uuid, long companyId)
        throws SystemException {
        for (Mensagem mensagem : findByUuid_C(uuid, companyId,
                QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
            remove(mensagem);
        }
    }

    /**
     * Returns the number of mensagems where uuid = &#63; and companyId = &#63;.
     *
     * @param uuid the uuid
     * @param companyId the company ID
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByUuid_C(String uuid, long companyId)
        throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_C;

        Object[] finderArgs = new Object[] { uuid, companyId };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(3);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            boolean bindUuid = false;

            if (uuid == null) {
                query.append(_FINDER_COLUMN_UUID_C_UUID_1);
            } else if (uuid.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_UUID_C_UUID_3);
            } else {
                bindUuid = true;

                query.append(_FINDER_COLUMN_UUID_C_UUID_2);
            }

            query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindUuid) {
                    qPos.add(uuid);
                }

                qPos.add(companyId);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns the mensagem where codigoMensagem = &#63; or throws a {@link br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException} if it could not be found.
     *
     * @param codigoMensagem the codigo mensagem
     * @return the matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByCodigo(String codigoMensagem)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByCodigo(codigoMensagem);

        if (mensagem == null) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("codigoMensagem=");
            msg.append(codigoMensagem);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            if (_log.isWarnEnabled()) {
                _log.warn(msg.toString());
            }

            throw new NoSuchMensagemException(msg.toString());
        }

        return mensagem;
    }

    /**
     * Returns the mensagem where codigoMensagem = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
     *
     * @param codigoMensagem the codigo mensagem
     * @return the matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByCodigo(String codigoMensagem)
        throws SystemException {
        return fetchByCodigo(codigoMensagem, true);
    }

    /**
     * Returns the mensagem where codigoMensagem = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
     *
     * @param codigoMensagem the codigo mensagem
     * @param retrieveFromCache whether to use the finder cache
     * @return the matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByCodigo(String codigoMensagem,
        boolean retrieveFromCache) throws SystemException {
        Object[] finderArgs = new Object[] { codigoMensagem };

        Object result = null;

        if (retrieveFromCache) {
            result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_CODIGO,
                    finderArgs, this);
        }

        if (result instanceof Mensagem) {
            Mensagem mensagem = (Mensagem) result;

            if (!Validator.equals(codigoMensagem, mensagem.getCodigoMensagem())) {
                result = null;
            }
        }

        if (result == null) {
            StringBundler query = new StringBundler(3);

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            boolean bindCodigoMensagem = false;

            if (codigoMensagem == null) {
                query.append(_FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_1);
            } else if (codigoMensagem.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_3);
            } else {
                bindCodigoMensagem = true;

                query.append(_FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_2);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindCodigoMensagem) {
                    qPos.add(codigoMensagem);
                }

                List<Mensagem> list = q.list();

                if (list.isEmpty()) {
                    FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_CODIGO,
                        finderArgs, list);
                } else {
                    Mensagem mensagem = list.get(0);

                    result = mensagem;

                    cacheResult(mensagem);

                    if ((mensagem.getCodigoMensagem() == null) ||
                            !mensagem.getCodigoMensagem().equals(codigoMensagem)) {
                        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_CODIGO,
                            finderArgs, mensagem);
                    }
                }
            } catch (Exception e) {
                FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_CODIGO,
                    finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        if (result instanceof List<?>) {
            return null;
        } else {
            return (Mensagem) result;
        }
    }

    /**
     * Removes the mensagem where codigoMensagem = &#63; from the database.
     *
     * @param codigoMensagem the codigo mensagem
     * @return the mensagem that was removed
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem removeByCodigo(String codigoMensagem)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByCodigo(codigoMensagem);

        return remove(mensagem);
    }

    /**
     * Returns the number of mensagems where codigoMensagem = &#63;.
     *
     * @param codigoMensagem the codigo mensagem
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByCodigo(String codigoMensagem) throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_CODIGO;

        Object[] finderArgs = new Object[] { codigoMensagem };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(2);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            boolean bindCodigoMensagem = false;

            if (codigoMensagem == null) {
                query.append(_FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_1);
            } else if (codigoMensagem.equals(StringPool.BLANK)) {
                query.append(_FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_3);
            } else {
                bindCodigoMensagem = true;

                query.append(_FINDER_COLUMN_CODIGO_CODIGOMENSAGEM_2);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                if (bindCodigoMensagem) {
                    qPos.add(codigoMensagem);
                }

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns all the mensagems where groupId = &#63;.
     *
     * @param groupId the group ID
     * @return the matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByGroupId(long groupId) throws SystemException {
        return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the mensagems where groupId = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param groupId the group ID
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @return the range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByGroupId(long groupId, int start, int end)
        throws SystemException {
        return findByGroupId(groupId, start, end, null);
    }

    /**
     * Returns an ordered range of all the mensagems where groupId = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param groupId the group ID
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByGroupId(long groupId, int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUPID;
            finderArgs = new Object[] { groupId };
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_GROUPID;
            finderArgs = new Object[] { groupId, start, end, orderByComparator };
        }

        List<Mensagem> list = (List<Mensagem>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if ((list != null) && !list.isEmpty()) {
            for (Mensagem mensagem : list) {
                if ((groupId != mensagem.getGroupId())) {
                    list = null;

                    break;
                }
            }
        }

        if (list == null) {
            StringBundler query = null;

            if (orderByComparator != null) {
                query = new StringBundler(3 +
                        (orderByComparator.getOrderByFields().length * 3));
            } else {
                query = new StringBundler(3);
            }

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_GROUPID_GROUPID_2);

            if (orderByComparator != null) {
                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);
            } else
             if (pagination) {
                query.append(MensagemModelImpl.ORDER_BY_JPQL);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(groupId);

                if (!pagination) {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<Mensagem>(list);
                } else {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Returns the first mensagem in the ordered set where groupId = &#63;.
     *
     * @param groupId the group ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByGroupId_First(long groupId,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByGroupId_First(groupId, orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("groupId=");
        msg.append(groupId);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the first mensagem in the ordered set where groupId = &#63;.
     *
     * @param groupId the group ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByGroupId_First(long groupId,
        OrderByComparator orderByComparator) throws SystemException {
        List<Mensagem> list = findByGroupId(groupId, 0, 1, orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the last mensagem in the ordered set where groupId = &#63;.
     *
     * @param groupId the group ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByGroupId_Last(long groupId,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByGroupId_Last(groupId, orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("groupId=");
        msg.append(groupId);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the last mensagem in the ordered set where groupId = &#63;.
     *
     * @param groupId the group ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByGroupId_Last(long groupId,
        OrderByComparator orderByComparator) throws SystemException {
        int count = countByGroupId(groupId);

        if (count == 0) {
            return null;
        }

        List<Mensagem> list = findByGroupId(groupId, count - 1, count,
                orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the mensagems before and after the current mensagem in the ordered set where groupId = &#63;.
     *
     * @param mensagemId the primary key of the current mensagem
     * @param groupId the group ID
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the previous, current, and next mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem[] findByGroupId_PrevAndNext(long mensagemId, long groupId,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByPrimaryKey(mensagemId);

        Session session = null;

        try {
            session = openSession();

            Mensagem[] array = new MensagemImpl[3];

            array[0] = getByGroupId_PrevAndNext(session, mensagem, groupId,
                    orderByComparator, true);

            array[1] = mensagem;

            array[2] = getByGroupId_PrevAndNext(session, mensagem, groupId,
                    orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected Mensagem getByGroupId_PrevAndNext(Session session,
        Mensagem mensagem, long groupId, OrderByComparator orderByComparator,
        boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_MENSAGEM_WHERE);

        query.append(_FINDER_COLUMN_GROUPID_GROUPID_2);

        if (orderByComparator != null) {
            String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

            if (orderByConditionFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByConditionFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByConditionFields[i]);

                if ((i + 1) < orderByConditionFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            String[] orderByFields = orderByComparator.getOrderByFields();

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        } else {
            query.append(MensagemModelImpl.ORDER_BY_JPQL);
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(groupId);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByConditionValues(mensagem);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<Mensagem> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    /**
     * Removes all the mensagems where groupId = &#63; from the database.
     *
     * @param groupId the group ID
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeByGroupId(long groupId) throws SystemException {
        for (Mensagem mensagem : findByGroupId(groupId, QueryUtil.ALL_POS,
                QueryUtil.ALL_POS, null)) {
            remove(mensagem);
        }
    }

    /**
     * Returns the number of mensagems where groupId = &#63;.
     *
     * @param groupId the group ID
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByGroupId(long groupId) throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_GROUPID;

        Object[] finderArgs = new Object[] { groupId };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(2);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_GROUPID_GROUPID_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(groupId);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns all the mensagems where statusWorkflow = &#63;.
     *
     * @param statusWorkflow the status workflow
     * @return the matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByStatusWorkflow(int statusWorkflow)
        throws SystemException {
        return findByStatusWorkflow(statusWorkflow, QueryUtil.ALL_POS,
            QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the mensagems where statusWorkflow = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param statusWorkflow the status workflow
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @return the range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByStatusWorkflow(int statusWorkflow, int start,
        int end) throws SystemException {
        return findByStatusWorkflow(statusWorkflow, start, end, null);
    }

    /**
     * Returns an ordered range of all the mensagems where statusWorkflow = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param statusWorkflow the status workflow
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByStatusWorkflow(int statusWorkflow, int start,
        int end, OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_STATUSWORKFLOW;
            finderArgs = new Object[] { statusWorkflow };
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_STATUSWORKFLOW;
            finderArgs = new Object[] {
                    statusWorkflow,
                    
                    start, end, orderByComparator
                };
        }

        List<Mensagem> list = (List<Mensagem>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if ((list != null) && !list.isEmpty()) {
            for (Mensagem mensagem : list) {
                if ((statusWorkflow != mensagem.getStatusWorkflow())) {
                    list = null;

                    break;
                }
            }
        }

        if (list == null) {
            StringBundler query = null;

            if (orderByComparator != null) {
                query = new StringBundler(3 +
                        (orderByComparator.getOrderByFields().length * 3));
            } else {
                query = new StringBundler(3);
            }

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_STATUSWORKFLOW_STATUSWORKFLOW_2);

            if (orderByComparator != null) {
                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);
            } else
             if (pagination) {
                query.append(MensagemModelImpl.ORDER_BY_JPQL);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(statusWorkflow);

                if (!pagination) {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<Mensagem>(list);
                } else {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Returns the first mensagem in the ordered set where statusWorkflow = &#63;.
     *
     * @param statusWorkflow the status workflow
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByStatusWorkflow_First(int statusWorkflow,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByStatusWorkflow_First(statusWorkflow,
                orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("statusWorkflow=");
        msg.append(statusWorkflow);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the first mensagem in the ordered set where statusWorkflow = &#63;.
     *
     * @param statusWorkflow the status workflow
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByStatusWorkflow_First(int statusWorkflow,
        OrderByComparator orderByComparator) throws SystemException {
        List<Mensagem> list = findByStatusWorkflow(statusWorkflow, 0, 1,
                orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the last mensagem in the ordered set where statusWorkflow = &#63;.
     *
     * @param statusWorkflow the status workflow
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByStatusWorkflow_Last(int statusWorkflow,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByStatusWorkflow_Last(statusWorkflow,
                orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("statusWorkflow=");
        msg.append(statusWorkflow);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the last mensagem in the ordered set where statusWorkflow = &#63;.
     *
     * @param statusWorkflow the status workflow
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByStatusWorkflow_Last(int statusWorkflow,
        OrderByComparator orderByComparator) throws SystemException {
        int count = countByStatusWorkflow(statusWorkflow);

        if (count == 0) {
            return null;
        }

        List<Mensagem> list = findByStatusWorkflow(statusWorkflow, count - 1,
                count, orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the mensagems before and after the current mensagem in the ordered set where statusWorkflow = &#63;.
     *
     * @param mensagemId the primary key of the current mensagem
     * @param statusWorkflow the status workflow
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the previous, current, and next mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem[] findByStatusWorkflow_PrevAndNext(long mensagemId,
        int statusWorkflow, OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByPrimaryKey(mensagemId);

        Session session = null;

        try {
            session = openSession();

            Mensagem[] array = new MensagemImpl[3];

            array[0] = getByStatusWorkflow_PrevAndNext(session, mensagem,
                    statusWorkflow, orderByComparator, true);

            array[1] = mensagem;

            array[2] = getByStatusWorkflow_PrevAndNext(session, mensagem,
                    statusWorkflow, orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected Mensagem getByStatusWorkflow_PrevAndNext(Session session,
        Mensagem mensagem, int statusWorkflow,
        OrderByComparator orderByComparator, boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_MENSAGEM_WHERE);

        query.append(_FINDER_COLUMN_STATUSWORKFLOW_STATUSWORKFLOW_2);

        if (orderByComparator != null) {
            String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

            if (orderByConditionFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByConditionFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByConditionFields[i]);

                if ((i + 1) < orderByConditionFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            String[] orderByFields = orderByComparator.getOrderByFields();

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        } else {
            query.append(MensagemModelImpl.ORDER_BY_JPQL);
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(statusWorkflow);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByConditionValues(mensagem);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<Mensagem> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    /**
     * Removes all the mensagems where statusWorkflow = &#63; from the database.
     *
     * @param statusWorkflow the status workflow
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeByStatusWorkflow(int statusWorkflow)
        throws SystemException {
        for (Mensagem mensagem : findByStatusWorkflow(statusWorkflow,
                QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
            remove(mensagem);
        }
    }

    /**
     * Returns the number of mensagems where statusWorkflow = &#63;.
     *
     * @param statusWorkflow the status workflow
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByStatusWorkflow(int statusWorkflow)
        throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_STATUSWORKFLOW;

        Object[] finderArgs = new Object[] { statusWorkflow };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(2);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_STATUSWORKFLOW_STATUSWORKFLOW_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(statusWorkflow);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns all the mensagems where userIdCriador = &#63;.
     *
     * @param userIdCriador the user ID criador
     * @return the matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUserIdCriador(long userIdCriador)
        throws SystemException {
        return findByUserIdCriador(userIdCriador, QueryUtil.ALL_POS,
            QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the mensagems where userIdCriador = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param userIdCriador the user ID criador
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @return the range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUserIdCriador(long userIdCriador, int start,
        int end) throws SystemException {
        return findByUserIdCriador(userIdCriador, start, end, null);
    }

    /**
     * Returns an ordered range of all the mensagems where userIdCriador = &#63;.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param userIdCriador the user ID criador
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findByUserIdCriador(long userIdCriador, int start,
        int end, OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_USERIDCRIADOR;
            finderArgs = new Object[] { userIdCriador };
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_USERIDCRIADOR;
            finderArgs = new Object[] {
                    userIdCriador,
                    
                    start, end, orderByComparator
                };
        }

        List<Mensagem> list = (List<Mensagem>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if ((list != null) && !list.isEmpty()) {
            for (Mensagem mensagem : list) {
                if ((userIdCriador != mensagem.getUserIdCriador())) {
                    list = null;

                    break;
                }
            }
        }

        if (list == null) {
            StringBundler query = null;

            if (orderByComparator != null) {
                query = new StringBundler(3 +
                        (orderByComparator.getOrderByFields().length * 3));
            } else {
                query = new StringBundler(3);
            }

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_USERIDCRIADOR_USERIDCRIADOR_2);

            if (orderByComparator != null) {
                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);
            } else
             if (pagination) {
                query.append(MensagemModelImpl.ORDER_BY_JPQL);
            }

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(userIdCriador);

                if (!pagination) {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<Mensagem>(list);
                } else {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Returns the first mensagem in the ordered set where userIdCriador = &#63;.
     *
     * @param userIdCriador the user ID criador
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUserIdCriador_First(long userIdCriador,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUserIdCriador_First(userIdCriador,
                orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("userIdCriador=");
        msg.append(userIdCriador);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the first mensagem in the ordered set where userIdCriador = &#63;.
     *
     * @param userIdCriador the user ID criador
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the first matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUserIdCriador_First(long userIdCriador,
        OrderByComparator orderByComparator) throws SystemException {
        List<Mensagem> list = findByUserIdCriador(userIdCriador, 0, 1,
                orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the last mensagem in the ordered set where userIdCriador = &#63;.
     *
     * @param userIdCriador the user ID criador
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByUserIdCriador_Last(long userIdCriador,
        OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByUserIdCriador_Last(userIdCriador,
                orderByComparator);

        if (mensagem != null) {
            return mensagem;
        }

        StringBundler msg = new StringBundler(4);

        msg.append(_NO_SUCH_ENTITY_WITH_KEY);

        msg.append("userIdCriador=");
        msg.append(userIdCriador);

        msg.append(StringPool.CLOSE_CURLY_BRACE);

        throw new NoSuchMensagemException(msg.toString());
    }

    /**
     * Returns the last mensagem in the ordered set where userIdCriador = &#63;.
     *
     * @param userIdCriador the user ID criador
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the last matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByUserIdCriador_Last(long userIdCriador,
        OrderByComparator orderByComparator) throws SystemException {
        int count = countByUserIdCriador(userIdCriador);

        if (count == 0) {
            return null;
        }

        List<Mensagem> list = findByUserIdCriador(userIdCriador, count - 1,
                count, orderByComparator);

        if (!list.isEmpty()) {
            return list.get(0);
        }

        return null;
    }

    /**
     * Returns the mensagems before and after the current mensagem in the ordered set where userIdCriador = &#63;.
     *
     * @param mensagemId the primary key of the current mensagem
     * @param userIdCriador the user ID criador
     * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
     * @return the previous, current, and next mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem[] findByUserIdCriador_PrevAndNext(long mensagemId,
        long userIdCriador, OrderByComparator orderByComparator)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByPrimaryKey(mensagemId);

        Session session = null;

        try {
            session = openSession();

            Mensagem[] array = new MensagemImpl[3];

            array[0] = getByUserIdCriador_PrevAndNext(session, mensagem,
                    userIdCriador, orderByComparator, true);

            array[1] = mensagem;

            array[2] = getByUserIdCriador_PrevAndNext(session, mensagem,
                    userIdCriador, orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected Mensagem getByUserIdCriador_PrevAndNext(Session session,
        Mensagem mensagem, long userIdCriador,
        OrderByComparator orderByComparator, boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_MENSAGEM_WHERE);

        query.append(_FINDER_COLUMN_USERIDCRIADOR_USERIDCRIADOR_2);

        if (orderByComparator != null) {
            String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

            if (orderByConditionFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByConditionFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByConditionFields[i]);

                if ((i + 1) < orderByConditionFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            String[] orderByFields = orderByComparator.getOrderByFields();

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        } else {
            query.append(MensagemModelImpl.ORDER_BY_JPQL);
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(userIdCriador);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByConditionValues(mensagem);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<Mensagem> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    /**
     * Removes all the mensagems where userIdCriador = &#63; from the database.
     *
     * @param userIdCriador the user ID criador
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeByUserIdCriador(long userIdCriador)
        throws SystemException {
        for (Mensagem mensagem : findByUserIdCriador(userIdCriador,
                QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
            remove(mensagem);
        }
    }

    /**
     * Returns the number of mensagems where userIdCriador = &#63;.
     *
     * @param userIdCriador the user ID criador
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByUserIdCriador(long userIdCriador)
        throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_USERIDCRIADOR;

        Object[] finderArgs = new Object[] { userIdCriador };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(2);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_USERIDCRIADOR_USERIDCRIADOR_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(userIdCriador);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Returns the mensagem where rascunho = &#63; and userIdCriador = &#63; or throws a {@link br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException} if it could not be found.
     *
     * @param rascunho the rascunho
     * @param userIdCriador the user ID criador
     * @return the matching mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByRascunhoCriador(boolean rascunho, long userIdCriador)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByRascunhoCriador(rascunho, userIdCriador);

        if (mensagem == null) {
            StringBundler msg = new StringBundler(6);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("rascunho=");
            msg.append(rascunho);

            msg.append(", userIdCriador=");
            msg.append(userIdCriador);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            if (_log.isWarnEnabled()) {
                _log.warn(msg.toString());
            }

            throw new NoSuchMensagemException(msg.toString());
        }

        return mensagem;
    }

    /**
     * Returns the mensagem where rascunho = &#63; and userIdCriador = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache.
     *
     * @param rascunho the rascunho
     * @param userIdCriador the user ID criador
     * @return the matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByRascunhoCriador(boolean rascunho, long userIdCriador)
        throws SystemException {
        return fetchByRascunhoCriador(rascunho, userIdCriador, true);
    }

    /**
     * Returns the mensagem where rascunho = &#63; and userIdCriador = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache.
     *
     * @param rascunho the rascunho
     * @param userIdCriador the user ID criador
     * @param retrieveFromCache whether to use the finder cache
     * @return the matching mensagem, or <code>null</code> if a matching mensagem could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByRascunhoCriador(boolean rascunho,
        long userIdCriador, boolean retrieveFromCache)
        throws SystemException {
        Object[] finderArgs = new Object[] { rascunho, userIdCriador };

        Object result = null;

        if (retrieveFromCache) {
            result = FinderCacheUtil.getResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                    finderArgs, this);
        }

        if (result instanceof Mensagem) {
            Mensagem mensagem = (Mensagem) result;

            if ((rascunho != mensagem.getRascunho()) ||
                    (userIdCriador != mensagem.getUserIdCriador())) {
                result = null;
            }
        }

        if (result == null) {
            StringBundler query = new StringBundler(4);

            query.append(_SQL_SELECT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_RASCUNHOCRIADOR_RASCUNHO_2);

            query.append(_FINDER_COLUMN_RASCUNHOCRIADOR_USERIDCRIADOR_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(rascunho);

                qPos.add(userIdCriador);

                List<Mensagem> list = q.list();

                if (list.isEmpty()) {
                    FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                        finderArgs, list);
                } else {
                    if ((list.size() > 1) && _log.isWarnEnabled()) {
                        _log.warn(
                            "MensagemPersistenceImpl.fetchByRascunhoCriador(boolean, long, boolean) with parameters (" +
                            StringUtil.merge(finderArgs) +
                            ") yields a result set with more than 1 result. This violates the logical unique restriction. There is no order guarantee on which result is returned by this finder.");
                    }

                    Mensagem mensagem = list.get(0);

                    result = mensagem;

                    cacheResult(mensagem);

                    if ((mensagem.getRascunho() != rascunho) ||
                            (mensagem.getUserIdCriador() != userIdCriador)) {
                        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                            finderArgs, mensagem);
                    }
                }
            } catch (Exception e) {
                FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                    finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        if (result instanceof List<?>) {
            return null;
        } else {
            return (Mensagem) result;
        }
    }

    /**
     * Removes the mensagem where rascunho = &#63; and userIdCriador = &#63; from the database.
     *
     * @param rascunho the rascunho
     * @param userIdCriador the user ID criador
     * @return the mensagem that was removed
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem removeByRascunhoCriador(boolean rascunho, long userIdCriador)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = findByRascunhoCriador(rascunho, userIdCriador);

        return remove(mensagem);
    }

    /**
     * Returns the number of mensagems where rascunho = &#63; and userIdCriador = &#63;.
     *
     * @param rascunho the rascunho
     * @param userIdCriador the user ID criador
     * @return the number of matching mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countByRascunhoCriador(boolean rascunho, long userIdCriador)
        throws SystemException {
        FinderPath finderPath = FINDER_PATH_COUNT_BY_RASCUNHOCRIADOR;

        Object[] finderArgs = new Object[] { rascunho, userIdCriador };

        Long count = (Long) FinderCacheUtil.getResult(finderPath, finderArgs,
                this);

        if (count == null) {
            StringBundler query = new StringBundler(3);

            query.append(_SQL_COUNT_MENSAGEM_WHERE);

            query.append(_FINDER_COLUMN_RASCUNHOCRIADOR_RASCUNHO_2);

            query.append(_FINDER_COLUMN_RASCUNHOCRIADOR_USERIDCRIADOR_2);

            String sql = query.toString();

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(rascunho);

                qPos.add(userIdCriador);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(finderPath, finderArgs, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    /**
     * Caches the mensagem in the entity cache if it is enabled.
     *
     * @param mensagem the mensagem
     */
    @Override
    public void cacheResult(Mensagem mensagem) {
        EntityCacheUtil.putResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemImpl.class, mensagem.getPrimaryKey(), mensagem);

        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_G,
            new Object[] { mensagem.getUuid(), mensagem.getGroupId() }, mensagem);

        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_CODIGO,
            new Object[] { mensagem.getCodigoMensagem() }, mensagem);

        FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
            new Object[] { mensagem.getRascunho(), mensagem.getUserIdCriador() },
            mensagem);

        mensagem.resetOriginalValues();
    }

    /**
     * Caches the mensagems in the entity cache if it is enabled.
     *
     * @param mensagems the mensagems
     */
    @Override
    public void cacheResult(List<Mensagem> mensagems) {
        for (Mensagem mensagem : mensagems) {
            if (EntityCacheUtil.getResult(
                        MensagemModelImpl.ENTITY_CACHE_ENABLED,
                        MensagemImpl.class, mensagem.getPrimaryKey()) == null) {
                cacheResult(mensagem);
            } else {
                mensagem.resetOriginalValues();
            }
        }
    }

    /**
     * Clears the cache for all mensagems.
     *
     * <p>
     * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
     * </p>
     */
    @Override
    public void clearCache() {
        if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
            CacheRegistryUtil.clear(MensagemImpl.class.getName());
        }

        EntityCacheUtil.clearCache(MensagemImpl.class.getName());

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
    }

    /**
     * Clears the cache for the mensagem.
     *
     * <p>
     * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
     * </p>
     */
    @Override
    public void clearCache(Mensagem mensagem) {
        EntityCacheUtil.removeResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemImpl.class, mensagem.getPrimaryKey());

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

        clearUniqueFindersCache(mensagem);
    }

    @Override
    public void clearCache(List<Mensagem> mensagems) {
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

        for (Mensagem mensagem : mensagems) {
            EntityCacheUtil.removeResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
                MensagemImpl.class, mensagem.getPrimaryKey());

            clearUniqueFindersCache(mensagem);
        }
    }

    protected void cacheUniqueFindersCache(Mensagem mensagem) {
        if (mensagem.isNew()) {
            Object[] args = new Object[] {
                    mensagem.getUuid(), mensagem.getGroupId()
                };

            FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
                Long.valueOf(1));
            FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_G, args,
                mensagem);

            args = new Object[] { mensagem.getCodigoMensagem() };

            FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_CODIGO, args,
                Long.valueOf(1));
            FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_CODIGO, args,
                mensagem);

            args = new Object[] {
                    mensagem.getRascunho(), mensagem.getUserIdCriador()
                };

            FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_RASCUNHOCRIADOR,
                args, Long.valueOf(1));
            FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                args, mensagem);
        } else {
            MensagemModelImpl mensagemModelImpl = (MensagemModelImpl) mensagem;

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
                Object[] args = new Object[] {
                        mensagem.getUuid(), mensagem.getGroupId()
                    };

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
                    Long.valueOf(1));
                FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_UUID_G, args,
                    mensagem);
            }

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_FETCH_BY_CODIGO.getColumnBitmask()) != 0) {
                Object[] args = new Object[] { mensagem.getCodigoMensagem() };

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_CODIGO, args,
                    Long.valueOf(1));
                FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_CODIGO, args,
                    mensagem);
            }

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR.getColumnBitmask()) != 0) {
                Object[] args = new Object[] {
                        mensagem.getRascunho(), mensagem.getUserIdCriador()
                    };

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_RASCUNHOCRIADOR,
                    args, Long.valueOf(1));
                FinderCacheUtil.putResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                    args, mensagem);
            }
        }
    }

    protected void clearUniqueFindersCache(Mensagem mensagem) {
        MensagemModelImpl mensagemModelImpl = (MensagemModelImpl) mensagem;

        Object[] args = new Object[] { mensagem.getUuid(), mensagem.getGroupId() };

        FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
        FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);

        if ((mensagemModelImpl.getColumnBitmask() &
                FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
            args = new Object[] {
                    mensagemModelImpl.getOriginalUuid(),
                    mensagemModelImpl.getOriginalGroupId()
                };

            FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
            FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
        }

        args = new Object[] { mensagem.getCodigoMensagem() };

        FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_CODIGO, args);
        FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_CODIGO, args);

        if ((mensagemModelImpl.getColumnBitmask() &
                FINDER_PATH_FETCH_BY_CODIGO.getColumnBitmask()) != 0) {
            args = new Object[] { mensagemModelImpl.getOriginalCodigoMensagem() };

            FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_CODIGO, args);
            FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_CODIGO, args);
        }

        args = new Object[] { mensagem.getRascunho(), mensagem.getUserIdCriador() };

        FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_RASCUNHOCRIADOR, args);
        FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR, args);

        if ((mensagemModelImpl.getColumnBitmask() &
                FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR.getColumnBitmask()) != 0) {
            args = new Object[] {
                    mensagemModelImpl.getOriginalRascunho(),
                    mensagemModelImpl.getOriginalUserIdCriador()
                };

            FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_RASCUNHOCRIADOR,
                args);
            FinderCacheUtil.removeResult(FINDER_PATH_FETCH_BY_RASCUNHOCRIADOR,
                args);
        }
    }

    /**
     * Creates a new mensagem with the primary key. Does not add the mensagem to the database.
     *
     * @param mensagemId the primary key for the new mensagem
     * @return the new mensagem
     */
    @Override
    public Mensagem create(long mensagemId) {
        Mensagem mensagem = new MensagemImpl();

        mensagem.setNew(true);
        mensagem.setPrimaryKey(mensagemId);

        String uuid = PortalUUIDUtil.generate();

        mensagem.setUuid(uuid);

        return mensagem;
    }

    /**
     * Removes the mensagem with the primary key from the database. Also notifies the appropriate model listeners.
     *
     * @param mensagemId the primary key of the mensagem
     * @return the mensagem that was removed
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem remove(long mensagemId)
        throws NoSuchMensagemException, SystemException {
        return remove((Serializable) mensagemId);
    }

    /**
     * Removes the mensagem with the primary key from the database. Also notifies the appropriate model listeners.
     *
     * @param primaryKey the primary key of the mensagem
     * @return the mensagem that was removed
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem remove(Serializable primaryKey)
        throws NoSuchMensagemException, SystemException {
        Session session = null;

        try {
            session = openSession();

            Mensagem mensagem = (Mensagem) session.get(MensagemImpl.class,
                    primaryKey);

            if (mensagem == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
                }

                throw new NoSuchMensagemException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                    primaryKey);
            }

            return remove(mensagem);
        } catch (NoSuchMensagemException nsee) {
            throw nsee;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    @Override
    protected Mensagem removeImpl(Mensagem mensagem) throws SystemException {
        mensagem = toUnwrappedModel(mensagem);

        Session session = null;

        try {
            session = openSession();

            if (!session.contains(mensagem)) {
                mensagem = (Mensagem) session.get(MensagemImpl.class,
                        mensagem.getPrimaryKeyObj());
            }

            if (mensagem != null) {
                session.delete(mensagem);
            }
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        if (mensagem != null) {
            clearCache(mensagem);
        }

        return mensagem;
    }

    @Override
    public Mensagem updateImpl(
        br.mp.mprj.portal.portlet.gestaomensagens.service.model.Mensagem mensagem)
        throws SystemException {
        mensagem = toUnwrappedModel(mensagem);

        boolean isNew = mensagem.isNew();

        MensagemModelImpl mensagemModelImpl = (MensagemModelImpl) mensagem;

        if (Validator.isNull(mensagem.getUuid())) {
            String uuid = PortalUUIDUtil.generate();

            mensagem.setUuid(uuid);
        }

        Session session = null;

        try {
            session = openSession();

            if (mensagem.isNew()) {
                session.save(mensagem);

                mensagem.setNew(false);
            } else {
                session.merge(mensagem);
            }
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);

        if (isNew || !MensagemModelImpl.COLUMN_BITMASK_ENABLED) {
            FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
        }
        else {
            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID.getColumnBitmask()) != 0) {
                Object[] args = new Object[] { mensagemModelImpl.getOriginalUuid() };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
                    args);

                args = new Object[] { mensagemModelImpl.getUuid() };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
                    args);
            }

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C.getColumnBitmask()) != 0) {
                Object[] args = new Object[] {
                        mensagemModelImpl.getOriginalUuid(),
                        mensagemModelImpl.getOriginalCompanyId()
                    };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
                    args);

                args = new Object[] {
                        mensagemModelImpl.getUuid(),
                        mensagemModelImpl.getCompanyId()
                    };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
                    args);
            }

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUPID.getColumnBitmask()) != 0) {
                Object[] args = new Object[] {
                        mensagemModelImpl.getOriginalGroupId()
                    };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_GROUPID, args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUPID,
                    args);

                args = new Object[] { mensagemModelImpl.getGroupId() };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_GROUPID, args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUPID,
                    args);
            }

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_STATUSWORKFLOW.getColumnBitmask()) != 0) {
                Object[] args = new Object[] {
                        mensagemModelImpl.getOriginalStatusWorkflow()
                    };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_STATUSWORKFLOW,
                    args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_STATUSWORKFLOW,
                    args);

                args = new Object[] { mensagemModelImpl.getStatusWorkflow() };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_STATUSWORKFLOW,
                    args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_STATUSWORKFLOW,
                    args);
            }

            if ((mensagemModelImpl.getColumnBitmask() &
                    FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_USERIDCRIADOR.getColumnBitmask()) != 0) {
                Object[] args = new Object[] {
                        mensagemModelImpl.getOriginalUserIdCriador()
                    };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_USERIDCRIADOR,
                    args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_USERIDCRIADOR,
                    args);

                args = new Object[] { mensagemModelImpl.getUserIdCriador() };

                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_USERIDCRIADOR,
                    args);
                FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_USERIDCRIADOR,
                    args);
            }
        }

        EntityCacheUtil.putResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
            MensagemImpl.class, mensagem.getPrimaryKey(), mensagem);

        clearUniqueFindersCache(mensagem);
        cacheUniqueFindersCache(mensagem);

        return mensagem;
    }

    protected Mensagem toUnwrappedModel(Mensagem mensagem) {
        if (mensagem instanceof MensagemImpl) {
            return mensagem;
        }

        MensagemImpl mensagemImpl = new MensagemImpl();

        mensagemImpl.setNew(mensagem.isNew());
        mensagemImpl.setPrimaryKey(mensagem.getPrimaryKey());

        mensagemImpl.setUuid(mensagem.getUuid());
        mensagemImpl.setMensagemId(mensagem.getMensagemId());
        mensagemImpl.setCompanyId(mensagem.getCompanyId());
        mensagemImpl.setGroupId(mensagem.getGroupId());
        mensagemImpl.setTemplateId(mensagem.getTemplateId());
        mensagemImpl.setGrupoDestinatarioIds(mensagem.getGrupoDestinatarioIds());
        mensagemImpl.setContaSaidaId(mensagem.getContaSaidaId());
        mensagemImpl.setCodigoMensagem(mensagem.getCodigoMensagem());
        mensagemImpl.setAssunto(mensagem.getAssunto());
        mensagemImpl.setConteudo(mensagem.getConteudo());
        mensagemImpl.setPrioridade(mensagem.getPrioridade());
        mensagemImpl.setAtivo(mensagem.isAtivo());
        mensagemImpl.setTipoEnvio(mensagem.getTipoEnvio());
        mensagemImpl.setSituacaoEnvio(mensagem.getSituacaoEnvio());
        mensagemImpl.setNomeSolicitante(mensagem.getNomeSolicitante());
        mensagemImpl.setUserIdCriador(mensagem.getUserIdCriador());
        mensagemImpl.setDataSolicitacao(mensagem.getDataSolicitacao());
        mensagemImpl.setDataUltimoEnvio(mensagem.getDataUltimoEnvio());
        mensagemImpl.setDataAlteracao(mensagem.getDataAlteracao());
        mensagemImpl.setRascunho(mensagem.isRascunho());
        mensagemImpl.setStatusWorkflow(mensagem.getStatusWorkflow());
        mensagemImpl.setUserIdWorkflow(mensagem.getUserIdWorkflow());
        mensagemImpl.setDataStatusWorkflow(mensagem.getDataStatusWorkflow());
        mensagemImpl.setComentarioWorkflow(mensagem.getComentarioWorkflow());
        mensagemImpl.setClonagemPai(mensagem.getClonagemPai());
        mensagemImpl.setLiteralAgendamento(mensagem.getLiteralAgendamento());
        mensagemImpl.setUserIdCancel(mensagem.getUserIdCancel());
        mensagemImpl.setUserIdAprovador(mensagem.getUserIdAprovador());
        mensagemImpl.setUserIdReprovador(mensagem.getUserIdReprovador());
        mensagemImpl.setDataCancel(mensagem.getDataCancel());
        mensagemImpl.setService(mensagem.isService());

        return mensagemImpl;
    }

    /**
     * Returns the mensagem with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
     *
     * @param primaryKey the primary key of the mensagem
     * @return the mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByPrimaryKey(Serializable primaryKey)
        throws NoSuchMensagemException, SystemException {
        Mensagem mensagem = fetchByPrimaryKey(primaryKey);

        if (mensagem == null) {
            if (_log.isWarnEnabled()) {
                _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
            }

            throw new NoSuchMensagemException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                primaryKey);
        }

        return mensagem;
    }

    /**
     * Returns the mensagem with the primary key or throws a {@link br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException} if it could not be found.
     *
     * @param mensagemId the primary key of the mensagem
     * @return the mensagem
     * @throws br.mp.mprj.portal.portlet.gestaomensagens.service.NoSuchMensagemException if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem findByPrimaryKey(long mensagemId)
        throws NoSuchMensagemException, SystemException {
        return findByPrimaryKey((Serializable) mensagemId);
    }

    /**
     * Returns the mensagem with the primary key or returns <code>null</code> if it could not be found.
     *
     * @param primaryKey the primary key of the mensagem
     * @return the mensagem, or <code>null</code> if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByPrimaryKey(Serializable primaryKey)
        throws SystemException {
        Mensagem mensagem = (Mensagem) EntityCacheUtil.getResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
                MensagemImpl.class, primaryKey);

        if (mensagem == _nullMensagem) {
            return null;
        }

        if (mensagem == null) {
            Session session = null;

            try {
                session = openSession();

                mensagem = (Mensagem) session.get(MensagemImpl.class, primaryKey);

                if (mensagem != null) {
                    cacheResult(mensagem);
                } else {
                    EntityCacheUtil.putResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
                        MensagemImpl.class, primaryKey, _nullMensagem);
                }
            } catch (Exception e) {
                EntityCacheUtil.removeResult(MensagemModelImpl.ENTITY_CACHE_ENABLED,
                    MensagemImpl.class, primaryKey);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return mensagem;
    }

    /**
     * Returns the mensagem with the primary key or returns <code>null</code> if it could not be found.
     *
     * @param mensagemId the primary key of the mensagem
     * @return the mensagem, or <code>null</code> if a mensagem with the primary key could not be found
     * @throws SystemException if a system exception occurred
     */
    @Override
    public Mensagem fetchByPrimaryKey(long mensagemId)
        throws SystemException {
        return fetchByPrimaryKey((Serializable) mensagemId);
    }

    /**
     * Returns all the mensagems.
     *
     * @return the mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findAll() throws SystemException {
        return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    /**
     * Returns a range of all the mensagems.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @return the range of mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findAll(int start, int end) throws SystemException {
        return findAll(start, end, null);
    }

    /**
     * Returns an ordered range of all the mensagems.
     *
     * <p>
     * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link br.mp.mprj.portal.portlet.gestaomensagens.service.model.impl.MensagemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
     * </p>
     *
     * @param start the lower bound of the range of mensagems
     * @param end the upper bound of the range of mensagems (not inclusive)
     * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
     * @return the ordered range of mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public List<Mensagem> findAll(int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        boolean pagination = true;
        FinderPath finderPath = null;
        Object[] finderArgs = null;

        if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
                (orderByComparator == null)) {
            pagination = false;
            finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
            finderArgs = FINDER_ARGS_EMPTY;
        } else {
            finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
            finderArgs = new Object[] { start, end, orderByComparator };
        }

        List<Mensagem> list = (List<Mensagem>) FinderCacheUtil.getResult(finderPath,
                finderArgs, this);

        if (list == null) {
            StringBundler query = null;
            String sql = null;

            if (orderByComparator != null) {
                query = new StringBundler(2 +
                        (orderByComparator.getOrderByFields().length * 3));

                query.append(_SQL_SELECT_MENSAGEM);

                appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                    orderByComparator);

                sql = query.toString();
            } else {
                sql = _SQL_SELECT_MENSAGEM;

                if (pagination) {
                    sql = sql.concat(MensagemModelImpl.ORDER_BY_JPQL);
                }
            }

            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(sql);

                if (!pagination) {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);

                    list = new UnmodifiableList<Mensagem>(list);
                } else {
                    list = (List<Mensagem>) QueryUtil.list(q, getDialect(),
                            start, end);
                }

                cacheResult(list);

                FinderCacheUtil.putResult(finderPath, finderArgs, list);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(finderPath, finderArgs);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return list;
    }

    /**
     * Removes all the mensagems from the database.
     *
     * @throws SystemException if a system exception occurred
     */
    @Override
    public void removeAll() throws SystemException {
        for (Mensagem mensagem : findAll()) {
            remove(mensagem);
        }
    }

    /**
     * Returns the number of mensagems.
     *
     * @return the number of mensagems
     * @throws SystemException if a system exception occurred
     */
    @Override
    public int countAll() throws SystemException {
        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
                FINDER_ARGS_EMPTY, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(_SQL_COUNT_MENSAGEM);

                count = (Long) q.uniqueResult();

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL,
                    FINDER_ARGS_EMPTY, count);
            } catch (Exception e) {
                FinderCacheUtil.removeResult(FINDER_PATH_COUNT_ALL,
                    FINDER_ARGS_EMPTY);

                throw processException(e);
            } finally {
                closeSession(session);
            }
        }

        return count.intValue();
    }

    @Override
    protected Set<String> getBadColumnNames() {
        return _badColumnNames;
    }

    /**
     * Initializes the mensagem persistence.
     */
    public void afterPropertiesSet() {
        String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
                    com.liferay.util.service.ServiceProps.get(
                        "value.object.listener.br.mp.mprj.portal.portlet.gestaomensagens.service.model.Mensagem")));

        if (listenerClassNames.length > 0) {
            try {
                List<ModelListener<Mensagem>> listenersList = new ArrayList<ModelListener<Mensagem>>();

                for (String listenerClassName : listenerClassNames) {
                    listenersList.add((ModelListener<Mensagem>) InstanceFactory.newInstance(
                            getClassLoader(), listenerClassName));
                }

                listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
            } catch (Exception e) {
                _log.error(e);
            }
        }
    }

    public void destroy() {
        EntityCacheUtil.removeCache(MensagemImpl.class.getName());
        FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
        FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
    }
}
