Search in sources :

Example 41 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class QueryOperation method initialize.

@Override
public void initialize(XRServiceAdapter xrService) {
    super.initialize(xrService);
    if (queryHandler == null) {
        // session query instead of named query
        DatabaseQuery dq = xrService.getORSession().getQuery(name);
        if (dq != null) {
            queryHandler = new QueryHandler() {

                @Override
                public void initializeDatabaseQuery(XRServiceAdapter xrService, QueryOperation queryOperation) {
                // do nothing
                }

                @Override
                public void initializeArguments(XRServiceAdapter xrService, QueryOperation queryOperation, DatabaseQuery databaseQuery) {
                // do nothing
                }

                @Override
                public void initializeCall(XRServiceAdapter xrService, QueryOperation queryOperation, DatabaseQuery databaseQuery) {
                // do nothing
                }
            };
            queryHandler.setDatabaseQuery(dq);
        }
    }
    if (queryHandler == null) {
        throw DBWSException.couldNotLocateQueryForSession(name, xrService.getORSession().getName());
    }
    queryHandler.initialize(xrService, this);
    Session oxSession = xrService.getOXSession();
    QName resultType = result == null ? null : result.getType();
    addSimpleXMLFormatModelDescriptor(xrService);
    addValueObjectDescriptor(xrService);
    if (resultType == null) {
        if (isAttachment()) {
            Attachment attachment = result.getAttachment();
            XMLDescriptor descriptor = (XMLDescriptor) oxSession.getProject().getClassDescriptor(DataHandler.class);
            if (descriptor == null) {
                descriptor = new XMLDescriptor();
                descriptor.setAlias(DATAHANDLER_STR);
                descriptor.setJavaClass(DataHandler.class);
                descriptor.setInstantiationPolicy(new DataHandlerInstantiationPolicy(attachment.getMimeType()));
                XMLBinaryDataMapping mapping = new XMLBinaryDataMapping();
                mapping.setAttributeName(RESULTS_STR);
                mapping.setAttributeAccessor(new AttributeAccessor() {

                    @Override
                    public Object getAttributeValueFromObject(Object object) throws DescriptorException {
                        Object result = null;
                        DataHandler dataHandler = (DataHandler) object;
                        try {
                            result = dataHandler.getContent();
                            if (result instanceof InputStream) {
                                try (InputStream is = (InputStream) result) {
                                    byte[] buf = new byte[2048];
                                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                    int bytesRead = is.read(buf);
                                    while (bytesRead >= 0) {
                                        baos.write(buf, 0, bytesRead);
                                        bytesRead = is.read(buf);
                                    }
                                    result = baos.toByteArray();
                                }
                            }
                        } catch (IOException e) {
                        // ignore
                        }
                        return result;
                    }

                    @Override
                    public void setAttributeValueInObject(Object object, Object value) throws DescriptorException {
                    }
                });
                mapping.setXPath(DEFAULT_SIMPLE_XML_FORMAT_TAG + SLASH_CHAR + DEFAULT_SIMPLE_XML_TAG + ATTACHMENT_STR);
                mapping.setSwaRef(true);
                mapping.setShouldInlineBinaryData(false);
                mapping.setMimeType(attachment.getMimeType());
                descriptor.addMapping(mapping);
                NamespaceResolver nr = new NamespaceResolver();
                descriptor.setNamespaceResolver(nr);
                oxSession.getProject().addDescriptor(descriptor);
                ((DatabaseSessionImpl) oxSession).initializeDescriptorIfSessionAlive(descriptor);
                xrService.getXMLContext().storeXMLDescriptorByQName(descriptor);
            }
        }
    }
}
Also used : DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) QName(javax.xml.namespace.QName) DescriptorException(org.eclipse.persistence.exceptions.DescriptorException) InputStream(java.io.InputStream) DataHandler(jakarta.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) XMLBinaryDataMapping(org.eclipse.persistence.oxm.mappings.XMLBinaryDataMapping) XMLDescriptor(org.eclipse.persistence.oxm.XMLDescriptor) DatabaseSessionImpl(org.eclipse.persistence.internal.sessions.DatabaseSessionImpl) NamespaceResolver(org.eclipse.persistence.oxm.NamespaceResolver) AttributeAccessor(org.eclipse.persistence.mappings.AttributeAccessor) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession) Session(org.eclipse.persistence.sessions.Session)

Example 42 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class TransactionIsolationBatchReadingTest method test.

@Override
public void test() {
    ReadAllQuery query = new ReadAllQuery(Employee.class);
    query.addBatchReadAttribute("address");
    Expression maleExp = (new ExpressionBuilder()).get("gender").equal("Male");
    Expression femaleExp = (new ExpressionBuilder()).get("gender").equal("Female");
    query.setSelectionCriteria(maleExp);
    Vector males = (Vector) getSession().executeQuery(query);
    Employee originalMale = (Employee) males.elementAt(0);
    Employee male = (Employee) unitOfWork.registerObject(originalMale);
    // read the males before early transaction started and the females after.
    unitOfWork.beginEarlyTransaction();
    query.setSelectionCriteria(femaleExp);
    Vector females = (Vector) unitOfWork.executeQuery(query);
    Employee female = (Employee) females.elementAt(0);
    Address maleAddress = male.getAddress();
    Address femaleAddress = female.getAddress();
    strongAssert((maleAddress != null), "The batch read attribute [male.address] was null");
    strongAssert((femaleAddress != null), "The batch read attribute [female.address] was null");
    strongAssert(male.address.isInstantiated(), "The wrapped valueholder should be instantiated, because it " + "was read on the session and is safe to trigger.");
    strongAssert(((UnitOfWorkImpl) unitOfWork).getBatchQueries() != null, "unitOfWork.getBatchReadObjects() must never return null");
    strongAssert(((UnitOfWorkImpl) unitOfWork).getBatchQueries().size() == 2, "unitOfWork batchReadObjects should only be storing the female addresses");
    if (!((UnitOfWorkImpl) unitOfWork).getBatchQueries().isEmpty()) {
        DatabaseQuery batchQuery = ((UnitOfWorkImpl) unitOfWork).getBatchQueries().keySet().iterator().next();
        strongAssert(batchQuery.getBatchObjects() == null, "triggering batch query on UOW should not store batched objects on the query.");
    }
    strongAssert((originalMale.getAddress() != maleAddress), "Triggering a valueholder on session is returning a clone from " + "the UnitOfWork batched objects.");
    Employee otherFemale = (Employee) females.elementAt(1);
    // Tests that batch querying actually works when in transaction.
    QueryCatcher queryCatcher = new QueryCatcher();
    unitOfWork.getEventManager().addListener(queryCatcher);
    try {
        otherFemale.getAddress();
    } finally {
        unitOfWork.getEventManager().removeListener(queryCatcher);
    }
}
Also used : Employee(org.eclipse.persistence.testing.models.employee.domain.Employee) Address(org.eclipse.persistence.testing.models.employee.domain.Address) Expression(org.eclipse.persistence.expressions.Expression) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) UnitOfWorkImpl(org.eclipse.persistence.internal.sessions.UnitOfWorkImpl) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) Vector(java.util.Vector)

Example 43 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class DescriptorQueryManager method addQuery.

/**
 * PUBLIC:
 * Add the query to the session queries
 * @param query DatabaseQuery This is the query that will be added.  If the query being added has parameters, the
 * existing list of queries will be checked for matching queries.  If a matching query exists,
 * it will be replaced.
 */
public synchronized void addQuery(DatabaseQuery query) {
    if (query instanceof ObjectLevelReadQuery && (query.getReferenceClassName() == null)) {
        ((ObjectLevelReadQuery) query).setReferenceClassName(getDescriptor().getJavaClassName());
        // case we will lazily initialize the reference class at a later point.
        try {
            ((ObjectLevelReadQuery) query).setReferenceClass(getDescriptor().getJavaClass());
        } catch (ConversionException exception) {
        }
        // this is an optimization
        query.setDescriptor(getDescriptor());
    }
    // Add query has been synchronized for bug 3355199.
    // Additionally code has been added to ensure that the same query is not added twice.
    List<DatabaseQuery> queriesByName = getQueries().get(query.getName());
    if (queriesByName == null) {
        // lazily create Vector in Hashtable.
        queriesByName = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
        getQueries().put(query.getName(), queriesByName);
    } else {
        int argumentTypesSize = 0;
        if (query.getArguments() != null) {
            argumentTypesSize = query.getArguments().size();
        }
        List<String> argumentTypes = new ArrayList<>(argumentTypesSize);
        for (int i = 0; i < argumentTypesSize; i++) {
            argumentTypes.add(query.getArgumentTypeNames().get(i));
        }
        // Search for a query with the same parameters and replace it if one is found
        for (int i = 0; i < queriesByName.size(); i++) {
            DatabaseQuery currentQuery = queriesByName.get(i);
            // replacing the exact same one. - TW
            if (argumentTypes.equals(currentQuery.getArgumentTypeNames())) {
                queriesByName.set(i, query);
                return;
            }
        }
    }
    queriesByName.add(query);
}
Also used : ObjectLevelReadQuery(org.eclipse.persistence.queries.ObjectLevelReadQuery) ConversionException(org.eclipse.persistence.exceptions.ConversionException) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) ArrayList(java.util.ArrayList)

Example 44 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class DescriptorQueryManager method populateQueries.

/**
 * INTERNAL:
 * populate the queries with the descriptor.
 */
private void populateQueries() {
    /* CR2260
         * Description:
         *   NullPointerException accessing null descriptor
         * Fix:
         *   Initialize queries with an instantiated descriptor at this point
         */
    if (getInsertQuery() != null) {
        getInsertQuery().setDescriptor(descriptor);
    }
    if (getUpdateQuery() != null) {
        getUpdateQuery().setDescriptor(descriptor);
    }
    if (getReadObjectQuery() != null) {
        getReadObjectQuery().setReferenceClass(getDescriptor().getJavaClass());
        getReadObjectQuery().setDescriptor(descriptor);
    }
    if (getDeleteQuery() != null) {
        getDeleteQuery().setDescriptor(descriptor);
    }
    if (getReadAllQuery() != null) {
        getReadAllQuery().setReferenceClass(getDescriptor().getJavaClass());
        getReadAllQuery().setDescriptor(descriptor);
    }
    for (Iterator it = getAllQueries().iterator(); it.hasNext(); ) {
        ((DatabaseQuery) it.next()).setDescriptor(descriptor);
    }
}
Also used : DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery) Iterator(java.util.Iterator)

Example 45 with DatabaseQuery

use of org.eclipse.persistence.queries.DatabaseQuery in project eclipselink by eclipse-ee4j.

the class NamedQueryHandler method initialize.

@Override
public void initialize(XRServiceAdapter xrService, QueryOperation queryOperation) {
    if (descriptor != null) {
        ClassDescriptor cd = xrService.getORSession().getProject().getDescriptorForAlias(descriptor);
        databaseQuery = cd.getQueryManager().getQuery(name);
    } else {
        databaseQuery = xrService.getORSession().getQuery(name);
        if (databaseQuery == null) {
            // must be a JPAQuery
            for (DatabaseQuery q : xrService.getORSession().getJPAQueries()) {
                if (q.getName().equals(name)) {
                    databaseQuery = q;
                    break;
                }
            }
        }
    }
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) DatabaseQuery(org.eclipse.persistence.queries.DatabaseQuery)

Aggregations

DatabaseQuery (org.eclipse.persistence.queries.DatabaseQuery)86 ArrayList (java.util.ArrayList)18 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)15 List (java.util.List)14 Vector (java.util.Vector)12 AbstractSession (org.eclipse.persistence.internal.sessions.AbstractSession)12 ObjectLevelReadQuery (org.eclipse.persistence.queries.ObjectLevelReadQuery)12 DatabaseField (org.eclipse.persistence.internal.helper.DatabaseField)8 EntityManager (jakarta.persistence.EntityManager)6 HashMap (java.util.HashMap)6 QName (javax.xml.namespace.QName)6 EJBQueryImpl (org.eclipse.persistence.internal.jpa.EJBQueryImpl)6 PersistenceContext (org.eclipse.persistence.jpa.rs.PersistenceContext)6 DataReadQuery (org.eclipse.persistence.queries.DataReadQuery)6 Session (org.eclipse.persistence.sessions.Session)6 Test (org.junit.Test)6 NonSynchronizedVector (org.eclipse.persistence.internal.helper.NonSynchronizedVector)5 ReadQuery (org.eclipse.persistence.queries.ReadQuery)5 ReportQuery (org.eclipse.persistence.queries.ReportQuery)5 PersistenceException (jakarta.persistence.PersistenceException)4