You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2017/03/14 08:52:18 UTC

[1/2] camel git commit: CAMEL-10265 Allow named queries in JPA Producer

Repository: camel
Updated Branches:
  refs/heads/master 6d052f093 -> 45e152211


CAMEL-10265 Allow named queries in JPA Producer

Added support for query, namedQuery and nativeQuery to the JPA producer. Now it also support Simple expression in the value of the parameters so it can retrieve a value from Message body, header and etc.


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/f976e47f
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/f976e47f
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/f976e47f

Branch: refs/heads/master
Commit: f976e47f4530a87cccb4dec9f3f5f8a2d598974a
Parents: 6d052f0
Author: Tomohisa Igarashi <tm...@gmail.com>
Authored: Tue Mar 14 16:21:18 2017 +0900
Committer: Claus Ibsen <da...@apache.org>
Committed: Tue Mar 14 09:50:07 2017 +0100

----------------------------------------------------------------------
 .../camel-jpa/src/main/docs/jpa-component.adoc  |  78 ++++++++-
 .../apache/camel/component/jpa/JpaConsumer.java |   2 +-
 .../apache/camel/component/jpa/JpaEndpoint.java |  50 ++++--
 .../apache/camel/component/jpa/JpaProducer.java | 148 ++++++++++++++++
 .../processor/jpa/JpaProducerWithQueryTest.java | 173 +++++++++++++++++++
 5 files changed, 430 insertions(+), 21 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/f976e47f/components/camel-jpa/src/main/docs/jpa-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-jpa/src/main/docs/jpa-component.adoc b/components/camel-jpa/src/main/docs/jpa-component.adoc
index 8495bf6..ae32505 100644
--- a/components/camel-jpa/src/main/docs/jpa-component.adoc
+++ b/components/camel-jpa/src/main/docs/jpa-component.adoc
@@ -36,6 +36,16 @@ If the body does not contain one of the previous listed types, put a
 link:message-translator.html[Message Translator] in front of the
 endpoint to perform the necessary conversion first.
 
+From *Camel 2.19* onwards you can use `query`, `namedQuery` or `nativeQuery`
+for the producer as well. Also in the value of the `parameters`, you can use
+Simple expression which allows you to retrieve parameter values from Message body, header
+and etc. Those query can be used for retrieving a set of data with using `SELECT`
+JPQL/SQL statement as well as executing bulk update/delete with using `UPDATE`/`DELETE`
+JPQL/SQL statement. Please note that you need to specify `useExecuteUpdate` to `true`
+if you execute `UPDATE`/`DELETE` with `namedQuery` as camel don't look into the
+named query unlike `query` and `nativeQuery`.
+
+
 ### Consuming from the endpoint
 
 Consuming messages from a JPA consumer endpoint removes (or updates)
@@ -121,27 +131,27 @@ with the following path and query parameters:
 | entityType |  | Class<?> | *Required* The JPA annotated class to use as entity.
 |=======================================================================
 
-#### Query Parameters (41 parameters):
+#### Query Parameters (42 parameters):
 
 [width="100%",cols="2,1,1m,1m,5",options="header"]
 |=======================================================================
 | Name | Group | Default | Java Type | Description
 | joinTransaction | common | true | boolean | The camel-jpa component will join transaction by default. You can use this option to turn this off for example if you use LOCAL_RESOURCE and join transaction doesn't work with your JPA provider. This option can also be set globally on the JpaComponent instead of having to set it on all endpoints.
+| maximumResults | common | 1 | int | Set the maximum number of results to retrieve on the Query.
+| namedQuery | common |  | String | To use a named query.
+| nativeQuery | common |  | String | To use a custom native query. You may want to use the option resultClass also when using native queries.
+| parameters | common |  | Map | This key/value mapping is used for building the query parameters. It is expected to be of the generic type java.util.Map where the keys are the named parameters of a given JPA query and the values are their corresponding effective values you want to select for. When it's used for producer Simple expression can be used as a parameter value. It allows you to retrieve parameter values from the message body header and etc.
 | persistenceUnit | common | camel | String | *Required* The JPA persistence unit used by default.
+| query | common |  | String | To use a custom query.
+| resultClass | common |  | Class<?> | Defines the type of the returned payload (we will call entityManager.createNativeQuery(nativeQuery resultClass) instead of entityManager.createNativeQuery(nativeQuery)). Without this option we will return an object array. Only has an affect when using in conjunction with native query when consuming data.
 | sharedEntityManager | common | false | boolean | Whether to use Spring's SharedEntityManager for the consumer/producer. Note in most cases joinTransaction should be set to false as this is not an EXTENDED EntityManager.
 | bridgeErrorHandler | consumer | false | boolean | Allows for bridging the consumer to the Camel routing Error Handler which mean any exceptions occurred while the consumer is trying to pickup incoming messages or the likes will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions that will be logged at WARN or ERROR level and ignored.
 | consumeDelete | consumer | true | boolean | If true the entity is deleted after it is consumed; if false the entity is not deleted.
 | consumeLockEntity | consumer | true | boolean | Specifies whether or not to set an exclusive lock on each entity bean while processing the results from polling.
 | deleteHandler | consumer |  | Object> | To use a custom DeleteHandler to delete the row after the consumer is done processing the exchange
 | lockModeType | consumer | PESSIMISTIC_WRITE | LockModeType | To configure the lock mode on the consumer.
-| maximumResults | consumer | -1 | int | Set the maximum number of results to retrieve on the Query.
 | maxMessagesPerPoll | consumer |  | int | An integer value to define the maximum number of messages to gather per poll. By default no maximum is set. Can be used to avoid polling many thousands of messages when starting up the server. Set a value of 0 or negative to disable.
-| namedQuery | consumer |  | String | To use a named query when consuming data.
-| nativeQuery | consumer |  | String | To use a custom native query when consuming data. You may want to use the option consumer.resultClass also when using native queries.
-| parameters | consumer |  | Map | This key/value mapping is used for building the query parameters. It's is expected to be of the generic type java.util.Map where the keys are the named parameters of a given JPA query and the values are their corresponding effective values you want to select for.
 | preDeleteHandler | consumer |  | Object> | To use a custom Pre-DeleteHandler to delete the row after the consumer has read the entity.
-| query | consumer |  | String | To use a custom query when consuming data.
-| resultClass | consumer |  | Class<?> | Defines the type of the returned payload (we will call entityManager.createNativeQuery(nativeQuery resultClass) instead of entityManager.createNativeQuery(nativeQuery)). Without this option we will return an object array. Only has an affect when using in conjunction with native query when consuming data.
 | sendEmptyMessageWhenIdle | consumer | false | boolean | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead.
 | skipLockedEntity | consumer | false | boolean | To configure whether to use NOWAIT on lock and silently skip the entity.
 | transacted | consumer | false | boolean | Whether to run the consumer in transacted mode by which all messages will either commit or rollback when the entire batch has been processed. The default behavior (false) is to commit all the previously successfully processed messages and only rollback the last failed message.
@@ -150,6 +160,7 @@ with the following path and query parameters:
 | pollStrategy | consumer (advanced) |  | PollingConsumerPollStrategy | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.
 | flushOnSend | producer | true | boolean | Flushes the EntityManager after the entity bean has been persisted.
 | remove | producer | false | boolean | Indicates to use entityManager.remove(entity).
+| useExecuteUpdate | producer |  | Boolean | To configure whether to use executeUpdate() when producer executes a query. When you use INSERT UPDATE or DELETE statement as a named query you need to specify this option to 'true'.
 | usePassedInEntityManager | producer | false | boolean | If set to true then Camel will use the EntityManager from the header JpaConstants.ENTITYMANAGER instead of the configured entity manager on the component/endpoint. This allows end users to control which entity manager will be in use.
 | usePersist | producer | false | boolean | Indicates to use entityManager.persist(entity) instead of entityManager.merge(entity). Note: entityManager.persist(entity) doesn't work for detached entities (where the EntityManager has to execute an UPDATE instead of an INSERT query)!
 | entityManagerProperties | advanced |  | Map | Additional properties for the entity manager to use.
@@ -291,6 +302,59 @@ from("jpa://org.apache.camel.examples.MultiSteps?consumer.nativeQuery=select * f
 If you use the native query option, you will receive an object array in
 the message body.
 
+
+### Using a producer with a named query
+
+For retrieving selected entities or execute bulk update/delete, you can use the
+`namedQuery` URI query option. First, you have to define the
+named query in the JPA Entity class:
+
+[source,java]
+----------------------------------------------------------------------------------
+@Entity
+@NamedQuery(name = "step1", query = "select x from MultiSteps x where x.step = 1")
+public class MultiSteps {
+   ...
+}
+----------------------------------------------------------------------------------
+
+After that you can define a producer uri like this one:
+
+[source,java]
+----------------------------------------------------------------------------
+from("direct:namedQuery")
+.to("jpa://org.apache.camel.examples.MultiSteps?namedQuery=step1");
+----------------------------------------------------------------------------
+
+Note that you need to specify `useExecuteUpdate` option to `true` to execute `UPDATE`/`DELETE` statement
+as a named query.
+
+### Using a producer with a query
+
+For retrieving selected entities or execute bulk update/delete, you can use the `query`
+URI query option. You only have to define the query option:
+
+[source,java]
+---------------------------------------------------------------------------------------------------------------------------------------
+from("direct:query")
+.to("jpa://org.apache.camel.examples.MultiSteps?query=select o from org.apache.camel.examples.MultiSteps o where o.step = 1");
+---------------------------------------------------------------------------------------------------------------------------------------
+
+### Using a producer with a native query
+
+For retrieving selected entities or execute bulk update/delete, you can use the
+`nativeQuery` URI query option. You only have to define the
+native query option:
+
+[source,java]
+---------------------------------------------------------------------------------------------------------------
+from("direct:nativeQuery")
+.to("jpa://org.apache.camel.examples.MultiSteps?resultClass=org.apache.camel.examples.MultiSteps&nativeQuery=select * from MultiSteps where step = 1");
+---------------------------------------------------------------------------------------------------------------
+
+If you use the native query option without specifying `resultClass`, you will receive an object array in
+the message body.
+
 ### Example
 
 See link:tracer-example.html[Tracer Example] for an example using

http://git-wip-us.apache.org/repos/asf/camel/blob/f976e47f/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java
----------------------------------------------------------------------
diff --git a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java
index f85d650..24b5b21 100644
--- a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java
+++ b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaConsumer.java
@@ -371,7 +371,7 @@ public class JpaConsumer extends ScheduledBatchPollingConsumer {
             if (resultClass != null) {
                 return QueryBuilder.nativeQuery(nativeQuery, resultClass);
             } else {
-                return QueryBuilder.nativeQuery(nativeQuery);                
+                return QueryBuilder.nativeQuery(nativeQuery);
             }
         } else {
             Class<?> entityType = getEndpoint().getEntityType();

http://git-wip-us.apache.org/repos/asf/camel/blob/f976e47f/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java
----------------------------------------------------------------------
diff --git a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java
index 1256b98..42631bb 100644
--- a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java
+++ b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaEndpoint.java
@@ -63,7 +63,7 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     private boolean joinTransaction = true;
     @UriParam
     private boolean sharedEntityManager;
-    @UriParam(label = "consumer", defaultValue = "-1")
+    @UriParam(defaultValue = "-1")
     private int maximumResults = -1;
     @UriParam(label = "consumer", defaultValue = "true")
     private boolean consumeDelete = true;
@@ -72,17 +72,17 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     @UriParam(label = "consumer")
     private int maxMessagesPerPoll;
 
-    @UriParam(label = "consumer", optionalPrefix = "consumer.")
+    @UriParam(optionalPrefix = "consumer.")
     private String query;
-    @UriParam(label = "consumer", optionalPrefix = "consumer.")
+    @UriParam(optionalPrefix = "consumer.")
     private String namedQuery;
-    @UriParam(label = "consumer", optionalPrefix = "consumer.")
+    @UriParam(optionalPrefix = "consumer.")
     private String nativeQuery;
     @UriParam(label = "consumer", optionalPrefix = "consumer.", defaultValue = "PESSIMISTIC_WRITE")
     private LockModeType lockModeType = LockModeType.PESSIMISTIC_WRITE;
-    @UriParam(label = "consumer", optionalPrefix = "consumer.", multiValue = true)
+    @UriParam(optionalPrefix = "consumer.", multiValue = true)
     private Map<String, Object> parameters;
-    @UriParam(label = "consumer", optionalPrefix = "consumer.")
+    @UriParam(optionalPrefix = "consumer.")
     private Class<?> resultClass;
     @UriParam(label = "consumer", optionalPrefix = "consumer.")
     private boolean transacted;
@@ -101,6 +101,8 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     private boolean usePassedInEntityManager;
     @UriParam(label = "producer")
     private boolean remove;
+    @UriParam(label = "producer")
+    private Boolean useExecuteUpdate;
 
     @UriParam(label = "advanced", prefix = "emf.", multiValue = true)
     private Map<String, Object> entityManagerProperties;
@@ -149,7 +151,14 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
 
     public Producer createProducer() throws Exception {
         validate();
-        return new JpaProducer(this, getProducerExpression());
+        JpaProducer producer = new JpaProducer(this, getProducerExpression());
+        producer.setQuery(getQuery());
+        producer.setNamedQuery(getNamedQuery());
+        producer.setNativeQuery(getNativeQuery());
+        producer.setParameters(getParameters());
+        producer.setResultClass(getResultClass());
+        producer.setUseExecuteUpdate(isUseExecuteUpdate());
+        return producer;
     }
 
     public Consumer createConsumer(Processor processor) throws Exception {
@@ -403,7 +412,7 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     }
 
     /**
-     * To use a custom query when consuming data.
+     * To use a custom query.
      */
     public void setQuery(String query) {
         this.query = query;
@@ -414,7 +423,7 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     }
 
     /**
-     * To use a named query when consuming data.
+     * To use a named query.
      */
     public void setNamedQuery(String namedQuery) {
         this.namedQuery = namedQuery;
@@ -425,7 +434,7 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     }
 
     /**
-     * To use a custom native query when consuming data. You may want to use the option consumer.resultClass also when using native queries.
+     * To use a custom native query. You may want to use the option resultClass also when using native queries.
      */
     public void setNativeQuery(String nativeQuery) {
         this.nativeQuery = nativeQuery;
@@ -447,9 +456,11 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
     }
 
     /**
-     * This key/value mapping is used for building the query parameters.
-     * It's is expected to be of the generic type java.util.Map<String, Object> where the keys are the named parameters
-     * of a given JPA query and the values are their corresponding effective values you want to select for.
+     * <p>This key/value mapping is used for building the query parameters.
+     * It is expected to be of the generic type java.util.Map<String, Object> where the keys are the named parameters
+     * of a given JPA query and the values are their corresponding effective values you want to select for.</p>
+     * <p>When it's used for producer, Simple expression can be used as a parameter value. It allows you to
+     * retrieve parameter values from the message body, header and etc.</p>
      */
     public void setParameters(Map<String, Object> parameters) {
         this.parameters = parameters;
@@ -514,6 +525,19 @@ public class JpaEndpoint extends ScheduledPollEndpoint {
         this.preDeleteHandler = preDeleteHandler;
     }
 
+    public Boolean isUseExecuteUpdate() {
+        return useExecuteUpdate;
+    }
+
+    /**
+     * To configure whether to use executeUpdate() when producer executes a query.
+     * When you use INSERT, UPDATE or DELETE statement as a named query, you need to specify
+     * this option to 'true'.
+     */
+    public void setUseExecuteUpdate(Boolean useExecuteUpdate) {
+        this.useExecuteUpdate = useExecuteUpdate;
+    }
+
     // Implementation methods
     // -------------------------------------------------------------------------
 

http://git-wip-us.apache.org/repos/asf/camel/blob/f976e47f/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaProducer.java
----------------------------------------------------------------------
diff --git a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaProducer.java b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaProducer.java
index 14fae7c..372fe91 100644
--- a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaProducer.java
+++ b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaProducer.java
@@ -17,12 +17,18 @@
 package org.apache.camel.component.jpa;
 
 import java.util.Collection;
+import java.util.Map;
+import java.util.Map.Entry;
+
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
+import javax.persistence.Query;
 
 import org.apache.camel.Exchange;
 import org.apache.camel.Expression;
+import org.apache.camel.Message;
 import org.apache.camel.impl.DefaultProducer;
+import org.apache.camel.language.simple.SimpleLanguage;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.transaction.TransactionStatus;
@@ -39,6 +45,13 @@ public class JpaProducer extends DefaultProducer {
     private final EntityManagerFactory entityManagerFactory;
     private final TransactionTemplate transactionTemplate;
     private final Expression expression;
+    private String query;
+    private String namedQuery;
+    private String nativeQuery;
+    private Map<String, Object> parameters;
+    private Class<?> resultClass;
+    private QueryFactory queryFactory;
+    private Boolean useExecuteUpdate;
 
     public JpaProducer(JpaEndpoint endpoint, Expression expression) {
         super(endpoint);
@@ -52,10 +65,145 @@ public class JpaProducer extends DefaultProducer {
         return (JpaEndpoint) super.getEndpoint();
     }
 
+    public QueryFactory getQueryFactory() {
+        if (queryFactory == null) {
+            if (query != null) {
+                queryFactory = QueryBuilder.query(query);
+            } else if (namedQuery != null) {
+                queryFactory = QueryBuilder.namedQuery(namedQuery);
+            } else if (nativeQuery != null) {
+                if (resultClass != null) {
+                    queryFactory = QueryBuilder.nativeQuery(nativeQuery, resultClass);
+                } else {
+                    queryFactory = QueryBuilder.nativeQuery(nativeQuery);
+                }
+            }
+        }
+        return queryFactory;
+    }
+
+    public void setQueryFactory(QueryFactory queryFactory) {
+        this.queryFactory = queryFactory;
+    }
+
+    public void setParameters(Map<String, Object> params) {
+        this.parameters = params;
+    }
+    
+    public Map<String, Object> getParameters() {
+        return parameters;
+    }
+
+    public String getNamedQuery() {
+        return namedQuery;
+    }
+
+    public void setNamedQuery(String namedQuery) {
+        this.namedQuery = namedQuery;
+    }
+
+    public String getNativeQuery() {
+        return nativeQuery;
+    }
+
+    public void setNativeQuery(String nativeQuery) {
+        this.nativeQuery = nativeQuery;
+    }
+
+    public String getQuery() {
+        return query;
+    }
+
+    public void setQuery(String query) {
+        this.query = query;
+    }
+    
+    public Class<?> getResultClass() {
+        return resultClass;
+    }
+
+    public void setResultClass(Class<?> resultClass) {
+        this.resultClass = resultClass;
+    }
+
+    public void setUseExecuteUpdate(Boolean executeUpdate) {
+        this.useExecuteUpdate = executeUpdate;
+    }
+
+    public boolean isUseExecuteUpdate() {
+        if (useExecuteUpdate == null) {
+            if (query != null) {
+                if (query.regionMatches(true, 0, "select", 0, 6)) {
+                    useExecuteUpdate = false;
+                } else {
+                    useExecuteUpdate = true;
+                }
+            } else if (nativeQuery != null) {
+                if (nativeQuery.regionMatches(true, 0, "select", 0, 6)) {
+                    useExecuteUpdate = false;
+                } else {
+                    useExecuteUpdate = true;
+                }
+            } else {
+                useExecuteUpdate = false;
+            }
+        }
+        return useExecuteUpdate;
+    }
+
     public void process(final Exchange exchange) {
         // resolve the entity manager before evaluating the expression
         final EntityManager entityManager = getTargetEntityManager(exchange, entityManagerFactory,
                 getEndpoint().isUsePassedInEntityManager(), getEndpoint().isSharedEntityManager(), true);
+
+        if (getQueryFactory() != null) {
+            processQuery(exchange, entityManager);
+        } else {
+            processEntity(exchange, entityManager);
+        }
+    }
+
+    protected void processQuery(Exchange exchange, EntityManager entityManager) {
+        Query query = getQueryFactory().createQuery(entityManager);
+        configureParameters(query, exchange);
+
+        transactionTemplate.execute(new TransactionCallback<Object>() {
+            public Object doInTransaction(TransactionStatus status) {
+                if (getEndpoint().isJoinTransaction()) {
+                    entityManager.joinTransaction();
+                }
+
+                Object answer = isUseExecuteUpdate() ? query.executeUpdate() : query.getResultList();
+                Message target = exchange.getPattern().isOutCapable() ? exchange.getOut() : exchange.getIn();
+                target.setBody(answer);
+
+                if (getEndpoint().isFlushOnSend()) {
+                    entityManager.flush();
+                }
+
+                return null;
+            }
+        });
+    }
+
+    private void configureParameters(Query query, Exchange exchange) {
+        int maxResults = getEndpoint().getMaximumResults();
+        if (maxResults > 0) {
+            query.setMaxResults(maxResults);
+        }
+        // setup the parameter
+        if (parameters != null) {
+            parameters.forEach((key, value) -> {
+                Object resolvedValue = value;
+                if (value instanceof String) {
+                    resolvedValue = SimpleLanguage.expression((String)value).evaluate(exchange, Object.class);
+                }
+                query.setParameter(key, resolvedValue);
+            });
+        }
+    }
+
+    protected void processEntity(Exchange exchange, EntityManager entityManager) {
         final Object values = expression.evaluate(exchange, Object.class);
 
         if (values != null) {

http://git-wip-us.apache.org/repos/asf/camel/blob/f976e47f/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerWithQueryTest.java
----------------------------------------------------------------------
diff --git a/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerWithQueryTest.java b/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerWithQueryTest.java
new file mode 100644
index 0000000..200ffb7
--- /dev/null
+++ b/components/camel-jpa/src/test/java/org/apache/camel/processor/jpa/JpaProducerWithQueryTest.java
@@ -0,0 +1,173 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.camel.processor.jpa;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import javax.persistence.EntityManager;
+
+import org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.examples.Customer;
+import org.apache.camel.examples.MultiSteps;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.impl.SimpleRegistry;
+import org.apache.camel.util.ServiceHelper;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.TransactionCallback;
+import org.springframework.transaction.support.TransactionTemplate;
+
+public class JpaProducerWithQueryTest extends Assert {
+    
+    protected static final Logger LOG = LoggerFactory.getLogger(JpaProducerWithQueryTest.class);
+    
+    protected DefaultCamelContext camelContext;
+    protected ProducerTemplate template;
+
+    @Test
+    public void testProducerWithNamedQuery() throws Exception {
+        template.sendBody("direct:deleteCustomers", "");
+        Customer c1 = new Customer();
+        c1.setName("Willem");
+        template.sendBody("direct:addCustomer", c1);
+        Customer c2 = new Customer();
+        c2.setName("Dummy");
+        template.sendBody("direct:addCustomer", c2);
+
+        Object answer = template.requestBody("direct:namedQuery", "Willem");
+        List list = (List)answer;
+        assertEquals(1, list.size());
+        assertEquals("Willem", ((Customer)list.get(0)).getName());
+
+        answer = template.requestBody("direct:deleteCustomers", "");
+        assertEquals(2, ((Integer)answer).intValue());
+    }
+
+    @Test
+    public void testProducerWithQuery() throws Exception {
+        template.sendBody("direct:deleteMultiSteps", "");
+        MultiSteps m1 = new MultiSteps();
+        m1.setStep(1);
+        template.sendBody("direct:addMultiSteps", m1);
+        MultiSteps m2 = new MultiSteps();
+        m2.setStep(2);
+        template.sendBody("direct:addMultiSteps", m2);
+
+        Object answer = template.requestBody("direct:query", "");
+        List list = (List)answer;
+        assertEquals(1, list.size());
+        assertEquals(1, ((MultiSteps)list.get(0)).getStep());
+
+        answer = template.requestBody("direct:deleteMultiSteps", "");
+        assertEquals(2, ((Integer)answer).intValue());
+    }
+
+    @Test
+    public void testProducerWithNativeQuery() throws Exception {
+        template.sendBody("direct:deleteMultiSteps", "");
+        MultiSteps m1 = new MultiSteps();
+        m1.setStep(1);
+        template.sendBody("direct:addMultiSteps", m1);
+        MultiSteps m2 = new MultiSteps();
+        m2.setStep(2);
+        template.sendBody("direct:addMultiSteps", m2);
+
+        Object answer = template.requestBody("direct:nativeQuery", "");
+        List list = (List)answer;
+        assertEquals(1, list.size());
+        assertEquals(1, ((Object[])list.get(0))[2]);
+
+        answer = template.requestBody("direct:deleteMultiSteps", "");
+        assertEquals(2, ((Integer)answer).intValue());
+    }
+
+    @Test
+    public void testProducerWithNativeQueryAndResultClass() throws Exception {
+        template.sendBody("direct:deleteMultiSteps", "");
+        MultiSteps m1 = new MultiSteps();
+        m1.setStep(1);
+        template.sendBody("direct:addMultiSteps", m1);
+        MultiSteps m2 = new MultiSteps();
+        m2.setStep(2);
+        template.sendBody("direct:addMultiSteps", m2);
+
+
+        Object answer = template.requestBody("direct:nativeQueryWithResultClass", "");
+        List list = (List)answer;
+        assertEquals(1, list.size());
+        assertEquals(1, ((MultiSteps)list.get(0)).getStep());
+
+        answer = template.requestBody("direct:deleteMultiSteps", "");
+        assertEquals(2, ((Integer)answer).intValue());
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        camelContext = new DefaultCamelContext();
+        SimpleRegistry registry = new SimpleRegistry();
+        Map<String, Object> params = new HashMap<String, Object>();
+        params.put("custName", "${body}");
+        // bind the params
+        registry.put("params", params);
+        camelContext.setRegistry(registry);
+
+        camelContext.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                from("direct:query")
+                    .to("jpa://" + MultiSteps.class.getName() + "?query=select o from " + MultiSteps.class.getName() + " o where o.step = 1");
+                from("direct:namedQuery")
+                    .to("jpa://" + Customer.class.getName() + "?namedQuery=findAllCustomersWithName&parameters=#params");
+                from("direct:nativeQuery")
+                    .to("jpa://" + MultiSteps.class.getName() + "?nativeQuery=select * from MultiSteps where step = 1");
+                from("direct:nativeQueryWithResultClass")
+                    .to("jpa://" + MultiSteps.class.getName() + "?resultClass=org.apache.camel.examples.MultiSteps&nativeQuery=select * from MultiSteps where step = 1");
+
+                from("direct:addCustomer")
+                    .to("jpa://" + Customer.class.getName());
+                from("direct:deleteCustomers")
+                    .to("jpa://" + Customer.class.getName() + "?query=delete from " + Customer.class.getName());
+                from("direct:addMultiSteps")
+                    .to("jpa://" + MultiSteps.class.getName());
+                from("direct:deleteMultiSteps")
+                    .to("jpa://" + MultiSteps.class.getName() + "?nativeQuery=delete from MultiSteps");
+            }
+        });
+
+        template = camelContext.createProducerTemplate();
+        ServiceHelper.startServices(template, camelContext);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        ServiceHelper.stopServices(template, camelContext);
+    }
+}


[2/2] camel git commit: CAMEL-10265: Regen docs

Posted by da...@apache.org.
CAMEL-10265: Regen docs


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/45e15221
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/45e15221
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/45e15221

Branch: refs/heads/master
Commit: 45e1522117a01575e5713dd9f7f7c75d2ec3ed1a
Parents: f976e47
Author: Claus Ibsen <da...@apache.org>
Authored: Tue Mar 14 09:51:47 2017 +0100
Committer: Claus Ibsen <da...@apache.org>
Committed: Tue Mar 14 09:51:47 2017 +0100

----------------------------------------------------------------------
 components/camel-jpa/src/main/docs/jpa-component.adoc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/45e15221/components/camel-jpa/src/main/docs/jpa-component.adoc
----------------------------------------------------------------------
diff --git a/components/camel-jpa/src/main/docs/jpa-component.adoc b/components/camel-jpa/src/main/docs/jpa-component.adoc
index ae32505..1f1dbb9 100644
--- a/components/camel-jpa/src/main/docs/jpa-component.adoc
+++ b/components/camel-jpa/src/main/docs/jpa-component.adoc
@@ -137,7 +137,7 @@ with the following path and query parameters:
 |=======================================================================
 | Name | Group | Default | Java Type | Description
 | joinTransaction | common | true | boolean | The camel-jpa component will join transaction by default. You can use this option to turn this off for example if you use LOCAL_RESOURCE and join transaction doesn't work with your JPA provider. This option can also be set globally on the JpaComponent instead of having to set it on all endpoints.
-| maximumResults | common | 1 | int | Set the maximum number of results to retrieve on the Query.
+| maximumResults | common | -1 | int | Set the maximum number of results to retrieve on the Query.
 | namedQuery | common |  | String | To use a named query.
 | nativeQuery | common |  | String | To use a custom native query. You may want to use the option resultClass also when using native queries.
 | parameters | common |  | Map | This key/value mapping is used for building the query parameters. It is expected to be of the generic type java.util.Map where the keys are the named parameters of a given JPA query and the values are their corresponding effective values you want to select for. When it's used for producer Simple expression can be used as a parameter value. It allows you to retrieve parameter values from the message body header and etc.