Package org.jpox.jpa

Source Code of org.jpox.jpa.JPAQuery

/**********************************************************************
Copyright (c) 2007 Andy Jefferson and others. All rights reserved.
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.

Contributors:
    ...
**********************************************************************/
package org.jpox.jpa;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.persistence.TemporalType;

import org.jpox.exceptions.JPOXException;
import org.jpox.store.query.JPOXQueryInvalidParametersException;
import org.jpox.store.query.NoQueryResultsException;
import org.jpox.store.query.QueryNotUniqueException;
import org.jpox.util.Localiser;
import org.jpox.util.StringUtils;

/**
* Basic implementation of a JPA Query.
* Wraps a JPOX query.
*
* @version $Revision: 1.1 $
*/
public class JPAQuery implements Query
{
    /** Localisation utility for output messages */
    protected static final Localiser LOCALISER = Localiser.getInstance("org.jpox.jpa.Localisation",
        JPOXJPAHelper.class.getClassLoader());

    /** Underlying EntityManager handling persistence. */
    EntityManager em;

    /** Query language. */
    String language;

    /** Underlying JPOX query providing the querying capability. */
    org.jpox.store.query.Query query;

    /** Flush mode for the query. */
    FlushModeType flushMode = FlushModeType.AUTO;

    /** The current start position. */
    private long startPosition = 0;

    /** The current max number of results. */
    private long maxResults = Long.MAX_VALUE;

    /**
     * Constructor for a query used by JPA.
     * @param em Entity Manager
     * @param query Underlying query
     * @param language Query language
     */
    public JPAQuery(EntityManager em, org.jpox.store.query.Query query, String language)
    {
        this.em = em;
        this.query = query;
        this.language = language;
    }

    /**
     * Method to execute a (UPDATE/DELETE) query returning the number of changed records.
     * @return Number of records updated/deleted with the query.
     */
    public int executeUpdate()
    {
        if (query.getType() == org.jpox.store.query.Query.SELECT)
        {
            throw new IllegalStateException(LOCALISER.msg("Query.ExecuteUpdateForSelectInvalid"));
        }

        try
        {
            if (flushMode == FlushModeType.AUTO && em.getTransaction().isActive())
            {
                em.flush();
            }

            Object result = query.executeWithMap(null); // Params defined using setParameter() earlier
            if (result != null)
            {
                return ((Long)result).intValue();
            }
            else
            {
                throw new JPOXException("Invalid return from query for an update/delete. Expected Long");
            }
        }
        catch (NoQueryResultsException nqre)
        {
            return 0;
        }
        catch (JPOXQueryInvalidParametersException ex)
        {
            throw new IllegalArgumentException(ex.getMessage(),ex);
        }
        catch (JPOXException jpe)
        {
            throw JPOXJPAHelper.getJPAExceptionForJPOXException(jpe);
        }
    }

    /**
     * Method to execute a (SELECT) query statement returning multiple results.
     * @return The results
     */
    public List getResultList()
    {
        if (query.getType() != org.jpox.store.query.Query.SELECT)
        {
            throw new IllegalStateException(LOCALISER.msg("Query.GetResultForUpdateInvalid"));
        }

        try
        {
            if (flushMode == FlushModeType.AUTO && em.getTransaction().isActive())
            {
                em.flush();
            }

            return (List)query.executeWithMap(null); // Params defined using setParameter() earlier
        }
        catch (NoQueryResultsException nqre)
        {
            return null;
        }
        catch (JPOXQueryInvalidParametersException ex)
        {
            throw new IllegalArgumentException(ex.getMessage(),ex);
        }
        catch (JPOXException jpe)
        {
            throw JPOXJPAHelper.getJPAExceptionForJPOXException(jpe);
        }
    }

    /**
     * Method to execute a SELECT statement returning a single result.
     * @return the result
     */
    public Object getSingleResult()
    {
        if (query.getType() != org.jpox.store.query.Query.SELECT)
        {
            throw new IllegalStateException(LOCALISER.msg("Query.GetResultForUpdateInvalid"));
        }

        try
        {
            if (flushMode == FlushModeType.AUTO && em.getTransaction().isActive())
            {
                em.flush();
            }

            query.setUnique(true);
            return query.executeWithMap(null); // Params defined using setParameter() earlier
        }
        catch (NoQueryResultsException nqre)
        {
            throw new NoResultException("No results for query: " + query.toString());
        }
        catch (QueryNotUniqueException ex)
        {
            throw new NonUniqueResultException("Expected a single result for query: " + query.toString() +
                " : " + StringUtils.getStringFromStackTrace(ex));
        }
        catch (JPOXQueryInvalidParametersException ex)
        {
            throw new IllegalArgumentException(ex.getMessage(),ex);
        }
        catch (JPOXException jpe)
        {
            throw JPOXJPAHelper.getJPAExceptionForJPOXException(jpe);
        }
    }

    /**
     * Method to set the results to start from a particular position.
     * @param startPosition position of first result numbered from 0
     * @return The query
     */
    public Query setFirstResult(int startPosition)
    {
        if (startPosition < 0)
        {
            throw new IllegalArgumentException(LOCALISER.msg("Query.StartPositionInvalid"));
        }

        this.startPosition = startPosition;
        query.setRange(this.startPosition, this.maxResults);
        return this;
    }

    /**
     * Method to set the max number of results to return.
     * @param max Number of results max
     * @return The query
     */
    public Query setMaxResults(int max)
    {
        if (max < 0)
        {
            throw new IllegalArgumentException(LOCALISER.msg("Query.MaxResultsInvalid"));
        }

        this.maxResults = max;
        query.setRange(startPosition, startPosition+max);
        return this;
    }

    /**
     * Mutator for the flush mode.
     * @param mode Flush mode
     * @return The query
     */
    public Query setFlushMode(FlushModeType mode)
    {
        flushMode = mode;
        return this;
    }

    /**
     * Method to add a vendor extension to the query.
     * If the hint name is not recognized, it is silently ignored.
     * @param hintName Name of the "hint"
     * @param value Value for the "hint"
     * @return the same query instance
     * @throws IllegalArgumentException if the second argument is not valid for the implementation
     */
    public Query setHint(String hintName, Object value)
    {
        // Just treat a "hint" as a JPOX "extension".
        query.addExtension(hintName, value);
        return this;
    }

    /**
     * Bind an argument to a named parameter.
     * @param name the parameter name
     * @param value The value for the param
     * @return the same query instance
     * @throws IllegalArgumentException
     *     if parameter name does not correspond to parameter in query string or argument is of incorrect type
     */
    public Query setParameter(String name, Object value)
    {
        try
        {
            query.setImplicitParameter(name, value);
        }
        catch (JPOXQueryInvalidParametersException ipe)
        {
            throw new IllegalArgumentException(ipe.getMessage());
        }
        return this;
    }

    /**
     * Bind an argument to a positional parameter.
     * @param position Parameter position
     * @param value The value
     * @return the same query instance
     * @throws IllegalArgumentException
     *     if position does not correspond to positional parameter of query or argument is of incorrect type
     */
    public Query setParameter(int position, Object value)
    {
        try
        {
            query.setImplicitParameter(position, value);
        }
        catch (JPOXQueryInvalidParametersException ipe)
        {
            throw new IllegalArgumentException(ipe.getMessage());
        }
        return this;
    }

    /**
     * Bind an instance of java.util.Date to a named parameter.
     * @param name Name of the param
     * @param value Value for the param
     * @param temporalType The temporal type
     * @return the same query instance
     * @throws IllegalArgumentException
     *     if parameter name does not correspond to parameter in query string
     */
    public Query setParameter(String name, Date value, TemporalType temporalType)
    {
        // TODO Use "temporalType"
        try
        {
            query.setImplicitParameter(name, value);
        }
        catch (JPOXQueryInvalidParametersException ipe)
        {
            throw new IllegalArgumentException(ipe.getMessage());
        }
        return this;
    }

    /**
     * Bind an instance of java.util.Calendar to a named parameter.
     * @param name name of the param
     * @param value Value for the param
     * @param temporalType The temporal type
     * @return the same query instance
     * @throws IllegalArgumentException
     *     if parameter name does not correspond to parameter in query string
     */
    public Query setParameter(String name, Calendar value, TemporalType temporalType)
    {
        // TODO Use "temporalType"
        try
        {
            query.setImplicitParameter(name, value);
        }
        catch (JPOXQueryInvalidParametersException ipe)
        {
            throw new IllegalArgumentException(ipe.getMessage());
        }
        return this;
    }

    /**
     * Bind an instance of java.util.Date to a positional parameter.
     * @param position Parameter position
     * @param value Value for the param
     * @param temporalType Temporal Type
     * @return the same query instance
     * @throws IllegalArgumentException
     *     if position does not correspond to positional parameter of query
     */
    public Query setParameter(int position, Date value, TemporalType temporalType)
    {
        // TODO Use "temporalType"
        try
        {
            query.setImplicitParameter(position, value);
        }
        catch (JPOXQueryInvalidParametersException ipe)
        {
            throw new IllegalArgumentException(ipe.getMessage());
        }
        return this;
    }

    /**
     * Bind an instance of java.util.Calendar to a positional parameter.
     * @param position Parameter position
     * @param value Value for the param
     * @param temporalType Temporal type
     * @return the same query instance
     * @throws IllegalArgumentException
     *     if position does not correspond to positional parameter of query
     */
    public Query setParameter(int position, Calendar value, TemporalType temporalType)
    {
        // TODO Use "temporalType"
        try
        {
            query.setImplicitParameter(position, value);
        }
        catch (JPOXQueryInvalidParametersException ipe)
        {
            throw new IllegalArgumentException(ipe.getMessage());
        }
        return this;
    }


    /**
     * Accessor for the query language.
     * @return Query language
     */
    public String getLanguage()
    {
        return language;
    }
}
TOP

Related Classes of org.jpox.jpa.JPAQuery

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.