net.navasoft.madcoin.backend.model.controller.impl.WorkRequestDataAccess.java Source code

Java tutorial

Introduction

Here is the source code for net.navasoft.madcoin.backend.model.controller.impl.WorkRequestDataAccess.java

Source

/*******************************************************************************
 * Copyright 2014 Juan Diego Navarre Gonzalez
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package net.navasoft.madcoin.backend.model.controller.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;

import net.navasoft.madcoin.backend.model.controller.exceptions.IllegalOrphanException;
import net.navasoft.madcoin.backend.model.controller.exceptions.InconsistentDataException;
import net.navasoft.madcoin.backend.model.controller.exceptions.NonexistentEntityException;
import net.navasoft.madcoin.backend.model.controller.helper.ComplexId;
import net.navasoft.madcoin.backend.model.controller.helper.impl.JPAHelper;
import net.navasoft.madcoin.backend.model.entities.CompleteNormalizedEntity;
import net.navasoft.madcoin.backend.model.entities.NormalizedEntity;
import net.navasoft.madcoin.backend.model.entities.ReferenceMode;
import net.navasoft.madcoin.backend.model.entities.impl.ServiceCategories;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestLocations;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequests;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsPK;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsXEndUsers;
import net.navasoft.madcoin.backend.model.entities.impl.WorkRequestsXServiceProviders;
import net.navasoft.madcoin.backend.services.rest.impl.IDataAccess;

import org.apache.commons.lang.NotImplementedException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * net.navasoft.madcoin.backend.model.controller.impl Class class
 * WorkRequestDataAccess. Description:
 * 
 * @author Juan Diego Navarre Gonzalez - (${authorMail})
 * @version 1.0
 * @since 2/09/2014 09:31:40 PM
 */
@Repository("ordersDAO")
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class WorkRequestDataAccess extends JPAHelper<WorkRequests> implements IDataAccess<WorkRequests> {

    /**
     * Instantiates a new work request data access.
     * 
     * @since 2/09/2014, 09:31:40 PM
     */
    public WorkRequestDataAccess() {
        storage = StorageFactory.buildStorage();
    }

    /**
     * entity manager.
     * 
     * @since 2/09/2014, 09:31:40 PM
     */
    @PersistenceContext(unitName = "ClickNDone-PU")
    private EntityManager entityManager;

    /**
     * storage.
     * 
     * @since 2/09/2014, 09:31:40 PM
     */
    private Storage storage;

    /**
     * Pre construct.
     * 
     * @param toInsert
     *            the to insert
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public void preConstruct(WorkRequests toInsert) {
        if (toInsert.getWorkRequestsPK() == null) {
            toInsert.setWorkRequestsPK(new WorkRequestsPK());
        }
        if (toInsert.getWorkRequestsXEndUsersCollection() == null) {
            toInsert.setWorkRequestsXEndUsersCollection(new ArrayList<WorkRequestsXEndUsers>());
        }
        if (toInsert.getWorkRequestsXServiceProvidersCollection() == null) {
            toInsert.setWorkRequestsXServiceProvidersCollection(new ArrayList<WorkRequestsXServiceProviders>());
        }

        toInsert.getWorkRequestsPK().setCategoryId(toInsert.getServiceCategories().getIdServiceCategory());
        try {
            try {
                ServiceCategories serviceCategories = toInsert.getServiceCategories();
                if (serviceCategories != null) {
                    serviceCategories = entityManager.getReference(serviceCategories.getClass(),
                            serviceCategories.getIdServiceCategory());
                    toInsert.setServiceCategories(serviceCategories);
                    storage.storeReference(WorkRequestStorageKeys.CATEGORY, ReferenceMode.NEW_REFERENCE,
                            serviceCategories);
                }
            } catch (EntityNotFoundException notfound) {
                System.out.println("categoria invalida");
                throw new NonexistentEntityException(notfound.getMessage());
            }

            // se hace posteriormente a la insercion de la orden...
            try {
                WorkRequestLocations workRequestLocations = toInsert.getWorkRequestLocations();
                if (workRequestLocations != null) {
                    workRequestLocations = entityManager.getReference(workRequestLocations.getClass(),
                            workRequestLocations.getWorkRequestLocationsPK());
                    toInsert.setWorkRequestLocations(workRequestLocations);
                    storage.storeReference(WorkRequestStorageKeys.LOCATION, ReferenceMode.NEW_REFERENCE,
                            workRequestLocations);
                }
            } catch (EntityNotFoundException notfound) {
                System.out.println("localizacion invalida");
                throw new NonexistentEntityException(notfound.getMessage());
            }

        } catch (NonexistentEntityException ne) {
            throw new InconsistentDataException(ne.getMessage());
        }

        Collection<WorkRequestsXEndUsers> generationUsers = new ArrayList<WorkRequestsXEndUsers>();
        for (WorkRequestsXEndUsers genUser : toInsert.getWorkRequestsXEndUsersCollection()) {
            genUser = entityManager.getReference(genUser.getClass(), genUser.getWorkRequestsXEndUsersPK());
            generationUsers.add(genUser);
        }
        toInsert.setWorkRequestsXEndUsersCollection(generationUsers);
        storage.storeReference(WorkRequestStorageKeys.END_USER, ReferenceMode.NEW_REFERENCE, generationUsers);

        // Cuando se crea la orden no se ingresa el proveedor, sin embargo, hay
        // que revisar si otros tipos de usuario final pueden escoger
        // inmediatamente...
        Collection<WorkRequestsXServiceProviders> attendingProvs = new ArrayList<WorkRequestsXServiceProviders>();
        for (WorkRequestsXServiceProviders provider : toInsert.getWorkRequestsXServiceProvidersCollection()) {
            provider = entityManager.getReference(provider.getClass(),
                    provider.getWorkRequestsXServiceProvidersPK());
            attendingProvs.add(provider);
        }
        toInsert.setWorkRequestsXServiceProvidersCollection(attendingProvs);
        storage.storeReference(WorkRequestStorageKeys.PROVIDER, ReferenceMode.NEW_REFERENCE, attendingProvs);
    }

    /**
     * Post construct.
     * 
     * @param inserted
     *            the inserted
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public void postConstruct(WorkRequests inserted) {

        ServiceCategories serviceCategories;
        WorkRequestLocations workRequestLocations;

        if (storage.validateReference(WorkRequestStorageKeys.CATEGORY, ReferenceMode.NEW_REFERENCE)) {
            serviceCategories = (ServiceCategories) storage.extractReference(WorkRequestStorageKeys.CATEGORY,
                    ReferenceMode.NEW_REFERENCE);
            serviceCategories.getWorkRequestsCollection().add(inserted);
            serviceCategories = entityManager.merge(serviceCategories);
        }

        if (storage.validateReference(WorkRequestStorageKeys.LOCATION, ReferenceMode.NEW_REFERENCE)) {
            workRequestLocations = (WorkRequestLocations) storage.extractReference(WorkRequestStorageKeys.LOCATION,
                    ReferenceMode.NEW_REFERENCE);
            WorkRequests order = workRequestLocations.getWorkRequests();
            if (order != null) {
                order.setWorkRequestLocations(null);
                order = entityManager.merge(order);
            }
            workRequestLocations.setWorkRequests(inserted);
            workRequestLocations = entityManager.merge(workRequestLocations);
        }

        for (WorkRequestsXEndUsers endUsers : inserted.getWorkRequestsXEndUsersCollection()) {
            WorkRequests order = endUsers.getWorkRequests();
            endUsers.setWorkRequests(inserted);
            endUsers = entityManager.merge(endUsers);
            if (order != null) {
                order.getWorkRequestsXEndUsersCollection().remove(endUsers);
                order = entityManager.merge(order);
            }
        }
        for (WorkRequestsXServiceProviders provider : inserted.getWorkRequestsXServiceProvidersCollection()) {
            WorkRequests order = provider.getWorkRequests();
            provider.setWorkRequests(inserted);
            provider = entityManager.merge(provider);
            if (order != null) {
                order.getWorkRequestsXServiceProvidersCollection().remove(provider);
                order = entityManager.merge(order);
            }
        }
        storage.clean();
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the work requests
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public WorkRequests preDelete(Number toDelete) throws NonexistentEntityException, IllegalOrphanException {
        throw new NotImplementedException();
    }

    /**
     * Pre delete.
     * 
     * @param toDelete
     *            the to delete
     * @return the work requests
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public WorkRequests preDelete(ComplexId toDelete) throws NonexistentEntityException, IllegalOrphanException {
        WorkRequests workRequests;
        try {
            workRequests = entityManager.getReference(WorkRequests.class, toDelete);
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException(
                    "The workRequests with id " + toDelete.resume() + " no longer exists.", enfe);
        }
        List<String> illegalOrphanMessages = null;

        WorkRequestLocations locationsRef = workRequests.getWorkRequestLocations();
        if (locationsRef != null) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This WorkRequests (" + workRequests
                    + ") cannot be destroyed since the WorkRequestLocations " + locationsRef.toString()
                    + " in its workRequestLocations field has a non-nullable workRequests field.");
        }
        Collection<WorkRequestsXEndUsers> endUsersRef = workRequests.getWorkRequestsXEndUsersCollection();
        for (WorkRequestsXEndUsers endUser : endUsersRef) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This WorkRequests (" + workRequests
                    + ") cannot be destroyed since the WorkRequestsXEndUsers " + endUser.toString()
                    + " in its workRequestsXEndUsersCollection field has a non-nullable workRequests field.");
        }

        Collection<WorkRequestsXServiceProviders> providerRef = workRequests
                .getWorkRequestsXServiceProvidersCollection();
        for (WorkRequestsXServiceProviders provider : providerRef) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This WorkRequests (" + workRequests
                    + ") cannot be destroyed since the WorkRequestsXServiceProviders " + provider.toString()
                    + " in its workRequestsXServiceProvidersCollection field has a non-nullable workRequests field.");
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }

        ServiceCategories serviceCategories = workRequests.getServiceCategories();
        if (serviceCategories != null) {
            serviceCategories.getWorkRequestsCollection().remove(workRequests);
            serviceCategories = entityManager.merge(serviceCategories);
        }
        return workRequests;
    }

    /**
     * Pre edit.
     * 
     * @param toEdit
     *            the to edit
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public void preEdit(WorkRequests toEdit) throws NonexistentEntityException, IllegalOrphanException {
        WorkRequests persistentWorkRequests = findByComplexId(entityManager, toEdit.getWorkRequestsPK(),
                WorkRequests.class);

        ServiceCategories serviceCategoriesOld = persistentWorkRequests.getServiceCategories();
        storage.storeReference(WorkRequestStorageKeys.CATEGORY, ReferenceMode.OLD_REFERENCE, serviceCategoriesOld);

        ServiceCategories serviceCategoriesNew = toEdit.getServiceCategories();

        WorkRequestLocations workRequestLocationsOld = persistentWorkRequests.getWorkRequestLocations();
        storage.storeReference(WorkRequestStorageKeys.LOCATION, ReferenceMode.OLD_REFERENCE,
                workRequestLocationsOld);

        WorkRequestLocations workRequestLocationsNew = toEdit.getWorkRequestLocations();

        Collection<WorkRequestsXEndUsers> workRequestsXEndUsersCollectionOld = persistentWorkRequests
                .getWorkRequestsXEndUsersCollection();
        storage.storeReference(WorkRequestStorageKeys.END_USER, ReferenceMode.OLD_REFERENCE,
                workRequestsXEndUsersCollectionOld);

        Collection<WorkRequestsXEndUsers> workRequestsXEndUsersCollectionNew = toEdit
                .getWorkRequestsXEndUsersCollection();

        Collection<WorkRequestsXServiceProviders> oldProvider = persistentWorkRequests
                .getWorkRequestsXServiceProvidersCollection();
        storage.storeReference(WorkRequestStorageKeys.PROVIDER, ReferenceMode.OLD_REFERENCE, oldProvider);

        Collection<WorkRequestsXServiceProviders> newProvider = toEdit.getWorkRequestsXServiceProvidersCollection();

        List<String> illegalOrphanMessages = null;

        if (workRequestLocationsOld != null && !workRequestLocationsOld.equals(workRequestLocationsNew)) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("You must retain WorkRequestLocations " + workRequestLocationsOld.toString()
                    + " since its workRequests field is not nullable.");
        }

        for (WorkRequestsXEndUsers user : workRequestsXEndUsersCollectionOld) {
            if (!workRequestsXEndUsersCollectionNew.contains(user)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain WorkRequestsXEndUsers " + user.toString()
                        + " since its workRequests field is not nullable.");
            }
        }

        for (WorkRequestsXServiceProviders oldProv : oldProvider) {
            if (!newProvider.contains(oldProv)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain WorkRequestsXServiceProviders " + oldProv.toString()
                        + " since its workRequests field is not nullable.");
            }
        }

        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }

        if (serviceCategoriesNew != null) {
            serviceCategoriesNew = entityManager.getReference(serviceCategoriesNew.getClass(),
                    serviceCategoriesNew.getIdServiceCategory());
            toEdit.setServiceCategories(serviceCategoriesNew);
            storage.storeReference(WorkRequestStorageKeys.CATEGORY, ReferenceMode.NEW_REFERENCE,
                    serviceCategoriesNew);
        }
        if (workRequestLocationsNew != null) {
            workRequestLocationsNew = entityManager.getReference(workRequestLocationsNew.getClass(),
                    workRequestLocationsNew.getWorkRequestLocationsPK());
            toEdit.setWorkRequestLocations(workRequestLocationsNew);
            storage.storeReference(WorkRequestStorageKeys.LOCATION, ReferenceMode.NEW_REFERENCE,
                    workRequestLocationsNew);
        }

        Collection<WorkRequestsXEndUsers> newUsers = new ArrayList<WorkRequestsXEndUsers>();
        for (WorkRequestsXEndUsers newUser : workRequestsXEndUsersCollectionNew) {
            newUser = entityManager.getReference(newUser.getClass(), newUser.getWorkRequestsXEndUsersPK());
            newUsers.add(newUser);
        }
        workRequestsXEndUsersCollectionNew = newUsers;
        toEdit.setWorkRequestsXEndUsersCollection(workRequestsXEndUsersCollectionNew);
        storage.storeReference(WorkRequestStorageKeys.END_USER, ReferenceMode.NEW_REFERENCE,
                workRequestsXEndUsersCollectionNew);

        Collection<WorkRequestsXServiceProviders> newProviders = new ArrayList<WorkRequestsXServiceProviders>();
        for (WorkRequestsXServiceProviders newProv : newProvider) {
            newProv = entityManager.getReference(newProv.getClass(), newProv.getWorkRequestsXServiceProvidersPK());
            newProviders.add(newProv);
        }
        newProvider = newProviders;
        toEdit.setWorkRequestsXServiceProvidersCollection(newProvider);
        storage.storeReference(WorkRequestStorageKeys.PROVIDER, ReferenceMode.NEW_REFERENCE, newProvider);
    }

    /**
     * Post edit.
     * 
     * @param entity
     *            the entity
     * @since 2/09/2014, 09:31:40 PM
     */
    @SuppressWarnings("unchecked")
    @Override
    public void postEdit(WorkRequests entity) {

        ServiceCategories serviceCategoriesOld;
        ServiceCategories serviceCategoriesNew;
        WorkRequestLocations workRequestLocationsNew;

        if (storage.compareReferences(WorkRequestStorageKeys.CATEGORY, ReferenceMode.OLD_REFERENCE)) {
            serviceCategoriesOld = (ServiceCategories) storage.extractReference(WorkRequestStorageKeys.CATEGORY,
                    ReferenceMode.OLD_REFERENCE);
            serviceCategoriesOld.getWorkRequestsCollection().remove(entity);
            serviceCategoriesOld = entityManager.merge(serviceCategoriesOld);
        }
        if (storage.compareReferences(WorkRequestStorageKeys.CATEGORY, ReferenceMode.NEW_REFERENCE)) {
            serviceCategoriesNew = (ServiceCategories) storage.extractReference(WorkRequestStorageKeys.CATEGORY,
                    ReferenceMode.NEW_REFERENCE);
            serviceCategoriesNew.getWorkRequestsCollection().add(entity);
            serviceCategoriesNew = entityManager.merge(serviceCategoriesNew);
        }
        if (storage.compareReferences(WorkRequestStorageKeys.LOCATION, ReferenceMode.NEW_REFERENCE)) {
            workRequestLocationsNew = (WorkRequestLocations) storage
                    .extractReference(WorkRequestStorageKeys.LOCATION, ReferenceMode.NEW_REFERENCE);
            WorkRequests oldOrder = workRequestLocationsNew.getWorkRequests();
            if (oldOrder != null) {
                oldOrder.setWorkRequestLocations(null);
                oldOrder = entityManager.merge(oldOrder);
            }
            workRequestLocationsNew.setWorkRequests(entity);
            workRequestLocationsNew = entityManager.merge(workRequestLocationsNew);
        }

        Collection<WorkRequestsXEndUsers> workRequestsXEndUsersCollectionOld = (Collection<WorkRequestsXEndUsers>) storage
                .extractReferences(WorkRequestStorageKeys.END_USER, ReferenceMode.OLD_REFERENCE);
        Collection<WorkRequestsXEndUsers> workRequestsXEndUsersCollectionNew = (Collection<WorkRequestsXEndUsers>) storage
                .extractReferences(WorkRequestStorageKeys.END_USER, ReferenceMode.NEW_REFERENCE);

        for (WorkRequestsXEndUsers endUsers : workRequestsXEndUsersCollectionNew) {
            if (!workRequestsXEndUsersCollectionOld.contains(endUsers)) {
                WorkRequests oldOrder = endUsers.getWorkRequests();
                endUsers.setWorkRequests(entity);
                endUsers = entityManager.merge(endUsers);
                if (oldOrder != null && !oldOrder.equals(entity)) {
                    oldOrder.getWorkRequestsXEndUsersCollection().remove(endUsers);
                    oldOrder = entityManager.merge(oldOrder);
                }
            }
        }

        Collection<WorkRequestsXServiceProviders> workRequestsXServiceProvidersCollectionOld = (Collection<WorkRequestsXServiceProviders>) storage
                .extractReferences(WorkRequestStorageKeys.PROVIDER, ReferenceMode.OLD_REFERENCE);
        Collection<WorkRequestsXServiceProviders> workRequestsXServiceProvidersCollectionNew = (Collection<WorkRequestsXServiceProviders>) storage
                .extractReferences(WorkRequestStorageKeys.PROVIDER, ReferenceMode.NEW_REFERENCE);

        for (WorkRequestsXServiceProviders provider : workRequestsXServiceProvidersCollectionNew) {
            if (!workRequestsXServiceProvidersCollectionOld.contains(provider)) {
                WorkRequests oldService = provider.getWorkRequests();
                provider.setWorkRequests(entity);
                provider = entityManager.merge(provider);
                if (oldService != null && !oldService.equals(entity)) {
                    oldService.getWorkRequestsXServiceProvidersCollection().remove(provider);
                    oldService = entityManager.merge(oldService);
                }
            }
        }
    }

    /**
     * Edits the.
     * 
     * @param updatedRecord
     *            the updated record
     * @return the work requests
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws Exception
     *             the exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public WorkRequests edit(WorkRequests updatedRecord) throws NonexistentEntityException, Exception {
        preEdit(updatedRecord);
        updatedRecord = entityManager.merge(updatedRecord);
        postEdit(updatedRecord);
        return updatedRecord;
    }

    /**
     * Gets the all.
     * 
     * @return the all
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public List<WorkRequests> getAll() {
        return super.getAllbyQuery(entityManager, WorkRequests.class);
    }

    /**
     * Gets the by logical id.
     * 
     * @param idEntity
     *            the id entity
     * @return the by logical id
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public WorkRequests getByLogicalId(Serializable idEntity) {
        if (idEntity instanceof WorkRequestsPK) {
            if (((WorkRequestsPK) idEntity).getIdWorkRequests() != 0) {
                TypedQuery<WorkRequests> query = entityManager.createNamedQuery(
                        "WorkRequests." + CompleteNormalizedEntity.COMPLETE_QUERY_ID, WorkRequests.class);
                query.setParameter("categoryId", ((WorkRequestsPK) idEntity).getCategoryId());
                query.setParameter("orderId", ((WorkRequestsPK) idEntity).getIdWorkRequests());
                List<WorkRequests> x = query.getResultList();
                return x.get(0);
            } else {
                TypedQuery<WorkRequests> query = entityManager
                        .createNamedQuery("WorkRequests." + NormalizedEntity.NAMED_QUERY_ID, WorkRequests.class);
                query.setParameter("categoryId", ((WorkRequestsPK) idEntity).getCategoryId());
                List<WorkRequests> x = query.getResultList();
                return x.get(0);
            }
        } else {
            Query query = entityManager.createNativeQuery(
                    "SELECT ORDERS.* FROM CLICKNDONEDB.WORK_REQUESTS ORDERS, CLICKNDONEDB.WORK_REQUESTS_X_END_USERS WHERE CATEGORY_ID = :categoryId",
                    WorkRequests.class);
            return (WorkRequests) query.getSingleResult();
        }
    }

    /**
     * Delete by id.
     * 
     * @param idEntity
     *            the id entity
     * @return the serializable
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Serializable deleteById(Serializable idEntity)
            throws NonexistentEntityException, IllegalOrphanException {
        WorkRequests deleted = preDelete((WorkRequestsPK) idEntity);
        entityManager.remove(deleted);
        entityManager.flush();
        return deleted;
    }

    /**
     * Creates the.
     * 
     * @param entity
     *            the entity
     * @return the work requests
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public WorkRequests create(WorkRequests entity) {
        preConstruct(entity);
        entityManager.persist(entity);
        entityManager.flush();
        entity = findLast(entityManager, WorkRequests.class, entity);
        postConstruct(entity);
        return entity;
    }

    /**
     * Find last.
     * 
     * @param dbAccess
     *            the db access
     * @param target
     *            the target
     * @param newRecord
     *            the new record
     * @return the work requests
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    protected WorkRequests findLast(EntityManager dbAccess, Class<WorkRequests> target, WorkRequests newRecord) {
        TypedQuery<WorkRequests> query = entityManager
                .createNamedQuery("WorkRequests." + NormalizedEntity.NAMED_QUERY_ID, target);
        query.setParameter("categoryId", newRecord.getWorkRequestsPK().getCategoryId());
        return query.getSingleResult();
    }

    /**
     * Delete all.
     * 
     * @throws NonexistentEntityException
     *             the nonexistent entity exception
     * @throws IllegalOrphanException
     *             the illegal orphan exception
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public void deleteAll() throws NonexistentEntityException, IllegalOrphanException {
        for (WorkRequests order : getAll()) {
            deleteById(order);
        }

    }

    /**
     * net.navasoft.madcoin.backend.model.controller.impl Enum enum
     * WorkRequestStorageKeys. Description:
     * 
     * @author Juan Diego Navarre Gonzalez - (${authorMail})
     * @version 1.0
     * @since 2/09/2014 09:31:40 PM
     */
    private enum WorkRequestStorageKeys implements StorageKeys {

        /**
         * category.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        CATEGORY("serviceCategories"),
        /**
         * location.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        LOCATION("workRequestLocations"),
        /**
         * end user.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        END_USER("endUser"),

        /**
         * provider.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        PROVIDER("provider");

        /**
         * key.
         * 
         * @since 2/09/2014, 09:31:40 PM
         */
        private String key;

        /**
         * Instantiates a new work request storage keys.
         * 
         * @param finalKey
         *            the final key
         * @since 2/09/2014, 09:31:40 PM
         */
        private WorkRequestStorageKeys(String finalKey) {
            key = finalKey;
        }

        /**
         * Gets the key.
         * 
         * @return the key
         * @since 2/09/2014, 09:31:40 PM
         */
        @Override
        public String getKey() {
            return key;
        }

    }

    /**
     * Count.
     * 
     * @return the int
     * @since 2/09/2014, 09:31:40 PM
     */
    @Override
    public int count() {
        return super.getQuantity(entityManager, WorkRequests.class);
    }

    /**
     * Gets the rows by criteria.
     * 
     * @return the rows by criteria
     * @since 9/09/2014, 11:22:17 AM
     */
    public List<WorkRequests> getRowsByCriteria() {
        CriteriaQuery<WorkRequests> cq = entityManager.getCriteriaBuilder().createQuery(WorkRequests.class);
        Root<WorkRequests> rt = cq.from(WorkRequests.class);
        cq.select(rt);
        ParameterExpression<String> status = entityManager.getCriteriaBuilder().parameter(String.class);
        cq.where(entityManager.getCriteriaBuilder().equal(rt.get("processStatus"), status));
        TypedQuery<WorkRequests> q = entityManager.createQuery(cq);
        return q.getResultList();
    }
}