davsclaus commented on code in PR #27314: URL: https://github.com/apache/camel/pull/27314#discussion_r4210390020
########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateProducer.java: ########## @@ -0,0 +1,266 @@ +/* + * 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.component.hibernate; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Stream; + +import org.apache.camel.Exchange; +import org.apache.camel.spi.Language; +import org.apache.camel.support.DefaultProducer; +import org.apache.camel.support.SynchronizationAdapter; +import org.hibernate.KeyType; +import org.hibernate.Session; +import org.hibernate.StatelessSession; +import org.hibernate.Transaction; +import org.hibernate.query.MutationQuery; +import org.hibernate.query.SelectionQuery; + +public class HibernateProducer extends DefaultProducer { + + private final HibernateEndpoint endpoint; + private Language simple; + + public HibernateProducer(HibernateEndpoint endpoint) { + super(endpoint); + this.endpoint = endpoint; + } + + @Override + protected void doBuild() throws Exception { + super.doBuild(); + simple = getEndpoint().getCamelContext().resolveLanguage("simple"); + } + + @Override + public void process(Exchange exchange) throws Exception { + if (endpoint.isStreaming() && exchange.isTransacted()) { + throw new IllegalArgumentException( + "streaming=true is not supported inside a transacted exchange because streams can outlive route transactions."); + } + + if (exchange.isTransacted() && !endpoint.isJta()) { + throw new IllegalStateException( + "Hibernate producer does not support transacted() exchanges with a resource-local SessionFactory."); + } + + if (endpoint.getStatelessOperation() != null) { + processStateless(exchange); + return; + } + + HibernateSessionContext sessionContext = exchange.getExchangeExtension() + .getSafeCopyProperty(HibernateConstants.HIBERNATE_SESSION_CONTEXT, HibernateSessionContext.class); + + Session session = sessionContext == null + ? null + : sessionContext.getSession( + endpoint.getSessionFactory(), + endpoint.getTenantIdentifier(), + endpoint.getFilters()); + + boolean sessionOwned = session == null; + + if (sessionOwned) { + session = endpoint.getTenantIdentifier() == null + ? endpoint.getSessionFactory().openSession() + : endpoint.getSessionFactory().withOptions() + .tenantIdentifier(endpoint.getTenantIdentifier()) + .openSession(); + } + + final Session activeSession = session; + final Transaction transaction = sessionOwned + ? activeSession.beginTransaction() + : activeSession.getTransaction(); + + try { + if (sessionOwned && endpoint.getFilters() != null) { + endpoint.getFilters().forEach((filterName, parameters) -> { + var filter = activeSession.enableFilter(filterName); + if (parameters != null) { + parameters.forEach(filter::setParameter); + } + }); + } + + @SuppressWarnings("unchecked") + Map<String, Object> parameters = exchange.getMessage().getHeader( + HibernateConstants.HIBERNATE_PARAMETERS, Map.class); + + if (endpoint.getNaturalIdParameters() != null) { + Object entity = activeSession.find( + endpoint.getEntityType(), + resolveNaturalIdParameters(exchange, parameters), + KeyType.NATURAL); + + exchange.getMessage().setBody(entity); + + if (sessionOwned) { + transaction.commit(); + activeSession.close(); + } + } else if (endpoint.getSelectionQuery() != null) { + SelectionQuery<?> query = activeSession.createSelectionQuery( + endpoint.getSelectionQuery(), endpoint.getEntityType()); + + if (sessionOwned) { + activeSession.setDefaultReadOnly(endpoint.isReadOnly()); + } + query.setReadOnly(endpoint.isReadOnly()); + + if (parameters != null) { + parameters.forEach(query::setParameter); + } + + if (endpoint.isStreaming()) { + if (sessionOwned) { + AtomicBoolean streamingSessionClosed = new AtomicBoolean(); + + exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() { + @Override + public void onComplete(Exchange exchange) { + closeStreamingSession( + activeSession, transaction, false, streamingSessionClosed); + } + + @Override + public void onFailure(Exchange exchange) { + closeStreamingSession( + activeSession, transaction, true, streamingSessionClosed); + } + }); + + Stream<?> stream = query.getResultStream(); + exchange.getMessage().setBody(stream.onClose( + () -> closeStreamingSession( + activeSession, transaction, false, streamingSessionClosed))); + } else { + exchange.getMessage().setBody(query.getResultStream()); + } + + return; + } + + exchange.getMessage().setBody(query.getResultList()); + + if (sessionOwned) { + transaction.commit(); + activeSession.close(); + } + } else { + MutationQuery query = activeSession.createMutationQuery(endpoint.getMutationQuery()); + + if (parameters != null) { + parameters.forEach(query::setParameter); + } + + exchange.getMessage().setBody(query.execute()); + + if (sessionOwned) { + transaction.commit(); + activeSession.close(); + } + } + } catch (Exception e) { + if (sessionOwned && transaction.isActive()) { + transaction.rollback(); + } + if (sessionOwned) { + activeSession.close(); + } + throw e; + } + } + + private Map<String, Object> resolveNaturalIdParameters(Exchange exchange, Map<String, Object> headerParameters) { + Map<String, Object> resolved = new LinkedHashMap<>(endpoint.getNaturalIdParameters()); + if (headerParameters != null) { + resolved.putAll(headerParameters); + } + Language language = simple(); + resolved.replaceAll((key, value) -> { + if (value instanceof String str) { + return language.createExpression(str).evaluate(exchange, Object.class); + } + return value; + }); Review Comment: Security: the `CamelHibernateParameters` header values are merged in before the Simple evaluation, so message data is evaluated as an expression (e.g. a header value `${bean:...}`). Only the endpoint-configured values are route configuration; please evaluate those and bind header values literally: ```suggestion Map<String, Object> resolved = new LinkedHashMap<>(endpoint.getNaturalIdParameters()); Language language = simple(); resolved.replaceAll((key, value) -> { if (value instanceof String str) { return language.createExpression(str).evaluate(exchange, Object.class); } return value; }); if (headerParameters != null) { // header values are message data, bind them as they are and never evaluate them resolved.putAll(headerParameters); } ``` A test with a header value containing `${...}` that asserts the literal value reaches the lookup would keep this in place. ########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateProducer.java: ########## @@ -0,0 +1,266 @@ +/* + * 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.component.hibernate; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Stream; + +import org.apache.camel.Exchange; +import org.apache.camel.spi.Language; +import org.apache.camel.support.DefaultProducer; +import org.apache.camel.support.SynchronizationAdapter; +import org.hibernate.KeyType; +import org.hibernate.Session; +import org.hibernate.StatelessSession; +import org.hibernate.Transaction; +import org.hibernate.query.MutationQuery; +import org.hibernate.query.SelectionQuery; + +public class HibernateProducer extends DefaultProducer { + + private final HibernateEndpoint endpoint; + private Language simple; + + public HibernateProducer(HibernateEndpoint endpoint) { + super(endpoint); + this.endpoint = endpoint; + } + + @Override + protected void doBuild() throws Exception { + super.doBuild(); + simple = getEndpoint().getCamelContext().resolveLanguage("simple"); + } + + @Override + public void process(Exchange exchange) throws Exception { + if (endpoint.isStreaming() && exchange.isTransacted()) { + throw new IllegalArgumentException( + "streaming=true is not supported inside a transacted exchange because streams can outlive route transactions."); + } + + if (exchange.isTransacted() && !endpoint.isJta()) { + throw new IllegalStateException( + "Hibernate producer does not support transacted() exchanges with a resource-local SessionFactory."); + } + + if (endpoint.getStatelessOperation() != null) { + processStateless(exchange); + return; + } + + HibernateSessionContext sessionContext = exchange.getExchangeExtension() + .getSafeCopyProperty(HibernateConstants.HIBERNATE_SESSION_CONTEXT, HibernateSessionContext.class); + + Session session = sessionContext == null + ? null + : sessionContext.getSession( + endpoint.getSessionFactory(), + endpoint.getTenantIdentifier(), + endpoint.getFilters()); + + boolean sessionOwned = session == null; + + if (sessionOwned) { + session = endpoint.getTenantIdentifier() == null + ? endpoint.getSessionFactory().openSession() + : endpoint.getSessionFactory().withOptions() + .tenantIdentifier(endpoint.getTenantIdentifier()) + .openSession(); + } + + final Session activeSession = session; + final Transaction transaction = sessionOwned + ? activeSession.beginTransaction() + : activeSession.getTransaction(); + + try { + if (sessionOwned && endpoint.getFilters() != null) { + endpoint.getFilters().forEach((filterName, parameters) -> { + var filter = activeSession.enableFilter(filterName); + if (parameters != null) { + parameters.forEach(filter::setParameter); + } + }); + } + + @SuppressWarnings("unchecked") + Map<String, Object> parameters = exchange.getMessage().getHeader( + HibernateConstants.HIBERNATE_PARAMETERS, Map.class); + + if (endpoint.getNaturalIdParameters() != null) { + Object entity = activeSession.find( + endpoint.getEntityType(), + resolveNaturalIdParameters(exchange, parameters), + KeyType.NATURAL); + + exchange.getMessage().setBody(entity); + + if (sessionOwned) { + transaction.commit(); + activeSession.close(); + } + } else if (endpoint.getSelectionQuery() != null) { + SelectionQuery<?> query = activeSession.createSelectionQuery( + endpoint.getSelectionQuery(), endpoint.getEntityType()); + + if (sessionOwned) { + activeSession.setDefaultReadOnly(endpoint.isReadOnly()); + } + query.setReadOnly(endpoint.isReadOnly()); + + if (parameters != null) { + parameters.forEach(query::setParameter); + } + + if (endpoint.isStreaming()) { + if (sessionOwned) { + AtomicBoolean streamingSessionClosed = new AtomicBoolean(); + + exchange.getExchangeExtension().addOnCompletion(new SynchronizationAdapter() { + @Override + public void onComplete(Exchange exchange) { + closeStreamingSession( + activeSession, transaction, false, streamingSessionClosed); + } + + @Override + public void onFailure(Exchange exchange) { + closeStreamingSession( + activeSession, transaction, true, streamingSessionClosed); + } + }); + + Stream<?> stream = query.getResultStream(); + exchange.getMessage().setBody(stream.onClose( + () -> closeStreamingSession( + activeSession, transaction, false, streamingSessionClosed))); + } else { + exchange.getMessage().setBody(query.getResultStream()); + } + + return; + } + + exchange.getMessage().setBody(query.getResultList()); + + if (sessionOwned) { + transaction.commit(); + activeSession.close(); + } + } else { + MutationQuery query = activeSession.createMutationQuery(endpoint.getMutationQuery()); + + if (parameters != null) { + parameters.forEach(query::setParameter); + } + + exchange.getMessage().setBody(query.execute()); + + if (sessionOwned) { + transaction.commit(); + activeSession.close(); + } + } + } catch (Exception e) { + if (sessionOwned && transaction.isActive()) { + transaction.rollback(); + } + if (sessionOwned) { + activeSession.close(); + } + throw e; + } + } + + private Map<String, Object> resolveNaturalIdParameters(Exchange exchange, Map<String, Object> headerParameters) { + Map<String, Object> resolved = new LinkedHashMap<>(endpoint.getNaturalIdParameters()); + if (headerParameters != null) { + resolved.putAll(headerParameters); + } + Language language = simple(); + resolved.replaceAll((key, value) -> { + if (value instanceof String str) { + return language.createExpression(str).evaluate(exchange, Object.class); + } + return value; + }); + return resolved; + } + + private Language simple() { Review Comment: Nit: `simple` is already resolved in `doBuild()`, so this lazy fallback is redundant. `createExpression(str)` also parses the endpoint values again for every exchange. The endpoint values are fixed, so they could be parsed once into `Expression`s (for example in `doStart()`), and the per-exchange path would only call `evaluate`. ########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateEndpoint.java: ########## @@ -0,0 +1,330 @@ +/* + * 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.component.hibernate; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.camel.Category; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.EndpointHelper; +import org.apache.camel.support.ScheduledPollEndpoint; +import org.apache.camel.util.PropertiesHelper; +import org.hibernate.SessionFactory; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder; + +@UriEndpoint(firstVersion = "4.24.0", scheme = "hibernate", title = "Hibernate", syntax = "hibernate:entityClassName", + category = { Category.DATABASE }, headersClass = HibernateConstants.class) +public class HibernateEndpoint extends ScheduledPollEndpoint { + + @UriPath(description = "Target entity class name or entity type name") + @Metadata(required = true) + private String entityClassName; + + @UriParam(description = "The HQL selection query to execute.", label = "producer,consumer") + private String selectionQuery; + + @UriParam(description = "The HQL mutation query to execute.", label = "producer") + private String mutationQuery; + + @UriParam(description = "The natural-id property values used for lookup. String values can use Simple expressions from the message.", + label = "producer", prefix = "naturalId.", multiValue = true) Review Comment: Question: values set through the `naturalId.` (and `filter.`) URI prefixes are always Strings, and `evaluate(exchange, Object.class)` keeps them that way. For a natural-id attribute or filter parameter that is not a String (e.g. a `Long` code), does Hibernate's `find(..., KeyType.NATURAL)` / `setParameter` convert the value, or does the lookup fail with a type mismatch? If it fails, converting to the attribute's Java type (from the entity metamodel) would help, or the docs could say that typed values need Java or `#bean` configuration. ########## components/camel-hibernate/src/test/java/org/apache/camel/component/hibernate/HibernateBootstrapTest.java: ########## @@ -0,0 +1,1286 @@ +/* + * 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.component.hibernate; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Route; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.hibernate.entity.HibernateTestEntity; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.engine.DefaultUnitOfWork; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.h2.jdbcx.JdbcDataSource; +import org.hibernate.Filter; +import org.hibernate.LockMode; +import org.hibernate.Session; +import org.hibernate.SessionBuilder; +import org.hibernate.SessionFactory; +import org.hibernate.Timeouts; +import org.hibernate.Transaction; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.query.MutationQuery; +import org.hibernate.query.SelectionQuery; +import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder; +import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class HibernateBootstrapTest extends CamelTestSupport { + + @Test + public void testExplicitSessionFactoryReuseAndNoClose() throws Exception { + SessionFactory mockSf = Mockito.mock(SessionFactory.class); + + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.setSessionFactory(mockSf); + comp.start(); + + assertSame(mockSf, comp.getSessionFactory()); + comp.stop(); + + Mockito.verify(mockSf, Mockito.never()).close(); + } + + @Test + public void testRegistrySessionFactoryReuseAndNoClose() throws Exception { + SessionFactory mockSf = Mockito.mock(SessionFactory.class); + context.getRegistry().bind("registrySf", mockSf); + + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.start(); + + assertSame(mockSf, comp.getSessionFactory()); + comp.stop(); + + Mockito.verify(mockSf, Mockito.never()).close(); + } + + @Test + public void testComponentCreatedSessionFactoryClosesOnStop() throws Exception { + HibernateComponent comp = createComponent("testDs", "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"); + + SessionFactory sf = comp.getSessionFactory(); + assertNotNull(sf); + assertFalse(sf.isClosed()); + + comp.stop(); + assertTrue(sf.isClosed()); + } + + @Test + public void testInvalidDataSourceRegistryNameFails() { + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.setDataSource("nonExistentDs"); + + Exception ex = assertThrows(Exception.class, comp::start); + assertTrue(ex.getMessage().contains("DataSource bean with name 'nonExistentDs' could not be found")); + } + + @Test + public void testInvalidSchemaActionFails() { + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.setSchemaAction("invalid-action"); + + Exception ex = assertThrows(Exception.class, comp::start); + assertTrue(ex.getMessage().contains("Invalid schemaAction")); + } + + @Test + public void testSelectionQueryProducer() throws Exception { + HibernateComponent comp = createComponent( + "selectionDs", + "jdbc:h2:mem:selectiondb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setSelectionQuery("from HibernateTestEntity"); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader(HibernateConstants.HIBERNATE_PARAMETERS, Map.of()); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + assertNotNull(exchange.getMessage().getBody()); + assertTrue(exchange.getMessage().getBody() instanceof java.util.List); + assertTrue(((java.util.List<?>) exchange.getMessage().getBody()).isEmpty()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testMutationQueryProducer() throws Exception { + HibernateComponent comp = createComponent( + "mutationDs", + "jdbc:h2:mem:mutationdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setMutationQuery("delete from HibernateTestEntity"); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader(HibernateConstants.HIBERNATE_PARAMETERS, Map.of()); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + assertEquals(0, exchange.getMessage().getBody()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testSchemaActionsAcceptedValues() { + String[] actions = { "none", "validate", "update", "create" }; + for (String action : actions) { + HibernateComponent comp = new HibernateComponent(); + comp.setSchemaAction(action); + assertEquals(action, comp.getSchemaAction()); + } + } + + @Test + public void testExplicitEntityClassesBootstrap() throws Exception { + HibernateComponent comp = createComponent( + "entityDs", + "jdbc:h2:mem:entitydb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + SessionFactory sf = comp.getSessionFactory(); + assertNotNull(sf); + assertNotNull(sf.getMetamodel().entity(HibernateTestEntity.class)); + + comp.stop(); + } + + @Test + public void testSelectionQueryProducerReadOnly() throws Exception { + HibernateComponent comp = createComponent( + "readOnlyDs", + "jdbc:h2:mem:readonlydb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setSelectionQuery("from HibernateTestEntity"); + endpoint.setReadOnly(true); + + endpoint.start(); + + assertTrue(endpoint.isReadOnly()); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader(HibernateConstants.HIBERNATE_PARAMETERS, Map.of()); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + assertNotNull(exchange.getMessage().getBody()); + assertTrue(exchange.getMessage().getBody() instanceof java.util.List); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testNaturalIdLookupProducer() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdDs", + "jdbc:h2:mem:naturaliddb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + Session session = comp.getSessionFactory().openSession(); + Transaction transaction = session.beginTransaction(); + + HibernateTestEntity entity = new HibernateTestEntity(); + entity.setId(1L); + entity.setName("test"); + session.persist(entity); + + transaction.commit(); + session.close(); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setNaturalIdParameters(Map.of("name", "test")); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + HibernateTestEntity result = exchange.getMessage().getBody(HibernateTestEntity.class); + + assertNotNull(result); + assertEquals(1L, result.getId()); + assertEquals("test", result.getName()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testNaturalIdPrefixUriBinding() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdPrefixDs", + "jdbc:h2:mem:naturalidprefixdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = (HibernateEndpoint) comp.createEndpoint( + "hibernate:" + HibernateTestEntity.class.getName() + "?naturalId.name=test"); + + assertEquals(Map.of("name", "test"), endpoint.getNaturalIdParameters()); + + comp.stop(); + } + + @Test + public void testNaturalIdBeanParameter() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdBeanDs", + "jdbc:h2:mem:naturalidbeandb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + context.getRegistry().bind("naturalIdMap", Map.of("name", "test")); + + HibernateEndpoint endpoint = (HibernateEndpoint) comp.createEndpoint( + "hibernate:" + HibernateTestEntity.class.getName() + "?naturalIdParameters=#naturalIdMap"); + + assertEquals(Map.of("name", "test"), endpoint.getNaturalIdParameters()); + + comp.stop(); + } + + @Test + public void testNaturalIdLookupFromMessageHeader() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdHeaderDs", + "jdbc:h2:mem:naturalidheaderdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + Session session = comp.getSessionFactory().openSession(); + Transaction transaction = session.beginTransaction(); + + HibernateTestEntity entity = new HibernateTestEntity(); + entity.setId(1L); + entity.setName("test"); + session.persist(entity); + + transaction.commit(); + session.close(); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setNaturalIdParameters(Map.of("name", "${header.lookupName}")); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader("lookupName", "test"); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + HibernateTestEntity result = exchange.getMessage().getBody(HibernateTestEntity.class); + + assertNotNull(result); + assertEquals(1L, result.getId()); + assertEquals("test", result.getName()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testSelectionQueryWithFilter() throws Exception { + HibernateComponent comp = createComponent( + "filterDs", + "jdbc:h2:mem:filterdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + Session session = comp.getSessionFactory().openSession(); + Transaction transaction = session.beginTransaction(); + + HibernateTestEntity first = new HibernateTestEntity(); + first.setId(1L); + first.setName("test"); + + HibernateTestEntity second = new HibernateTestEntity(); + second.setId(2L); + second.setName("other"); + + session.persist(first); + session.persist(second); + + transaction.commit(); + session.close(); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setSelectionQuery("from HibernateTestEntity"); + endpoint.setFilters(Map.of("nameFilter", Map.of("name", "test"))); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + java.util.List<?> results = exchange.getMessage().getBody(java.util.List.class); Review Comment: `java.util.List` is already imported, please use the simple name (CLAUDE.md import style): ```suggestion List<?> results = exchange.getMessage().getBody(List.class); ``` ########## components/camel-hibernate/src/test/java/org/apache/camel/component/hibernate/HibernateBootstrapTest.java: ########## @@ -0,0 +1,1286 @@ +/* + * 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.component.hibernate; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import org.apache.camel.Consumer; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Route; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.hibernate.entity.HibernateTestEntity; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.engine.DefaultUnitOfWork; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.h2.jdbcx.JdbcDataSource; +import org.hibernate.Filter; +import org.hibernate.LockMode; +import org.hibernate.Session; +import org.hibernate.SessionBuilder; +import org.hibernate.SessionFactory; +import org.hibernate.Timeouts; +import org.hibernate.Transaction; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.query.MutationQuery; +import org.hibernate.query.SelectionQuery; +import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder; +import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class HibernateBootstrapTest extends CamelTestSupport { + + @Test + public void testExplicitSessionFactoryReuseAndNoClose() throws Exception { + SessionFactory mockSf = Mockito.mock(SessionFactory.class); + + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.setSessionFactory(mockSf); + comp.start(); + + assertSame(mockSf, comp.getSessionFactory()); + comp.stop(); + + Mockito.verify(mockSf, Mockito.never()).close(); + } + + @Test + public void testRegistrySessionFactoryReuseAndNoClose() throws Exception { + SessionFactory mockSf = Mockito.mock(SessionFactory.class); + context.getRegistry().bind("registrySf", mockSf); + + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.start(); + + assertSame(mockSf, comp.getSessionFactory()); + comp.stop(); + + Mockito.verify(mockSf, Mockito.never()).close(); + } + + @Test + public void testComponentCreatedSessionFactoryClosesOnStop() throws Exception { + HibernateComponent comp = createComponent("testDs", "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"); + + SessionFactory sf = comp.getSessionFactory(); + assertNotNull(sf); + assertFalse(sf.isClosed()); + + comp.stop(); + assertTrue(sf.isClosed()); + } + + @Test + public void testInvalidDataSourceRegistryNameFails() { + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.setDataSource("nonExistentDs"); + + Exception ex = assertThrows(Exception.class, comp::start); + assertTrue(ex.getMessage().contains("DataSource bean with name 'nonExistentDs' could not be found")); + } + + @Test + public void testInvalidSchemaActionFails() { + HibernateComponent comp = new HibernateComponent(); + comp.setCamelContext(context); + comp.setSchemaAction("invalid-action"); + + Exception ex = assertThrows(Exception.class, comp::start); + assertTrue(ex.getMessage().contains("Invalid schemaAction")); + } + + @Test + public void testSelectionQueryProducer() throws Exception { + HibernateComponent comp = createComponent( + "selectionDs", + "jdbc:h2:mem:selectiondb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setSelectionQuery("from HibernateTestEntity"); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader(HibernateConstants.HIBERNATE_PARAMETERS, Map.of()); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + assertNotNull(exchange.getMessage().getBody()); + assertTrue(exchange.getMessage().getBody() instanceof java.util.List); + assertTrue(((java.util.List<?>) exchange.getMessage().getBody()).isEmpty()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testMutationQueryProducer() throws Exception { + HibernateComponent comp = createComponent( + "mutationDs", + "jdbc:h2:mem:mutationdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setMutationQuery("delete from HibernateTestEntity"); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader(HibernateConstants.HIBERNATE_PARAMETERS, Map.of()); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + assertEquals(0, exchange.getMessage().getBody()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testSchemaActionsAcceptedValues() { + String[] actions = { "none", "validate", "update", "create" }; + for (String action : actions) { + HibernateComponent comp = new HibernateComponent(); + comp.setSchemaAction(action); + assertEquals(action, comp.getSchemaAction()); + } + } + + @Test + public void testExplicitEntityClassesBootstrap() throws Exception { + HibernateComponent comp = createComponent( + "entityDs", + "jdbc:h2:mem:entitydb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + SessionFactory sf = comp.getSessionFactory(); + assertNotNull(sf); + assertNotNull(sf.getMetamodel().entity(HibernateTestEntity.class)); + + comp.stop(); + } + + @Test + public void testSelectionQueryProducerReadOnly() throws Exception { + HibernateComponent comp = createComponent( + "readOnlyDs", + "jdbc:h2:mem:readonlydb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setSelectionQuery("from HibernateTestEntity"); + endpoint.setReadOnly(true); + + endpoint.start(); + + assertTrue(endpoint.isReadOnly()); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader(HibernateConstants.HIBERNATE_PARAMETERS, Map.of()); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + assertNotNull(exchange.getMessage().getBody()); + assertTrue(exchange.getMessage().getBody() instanceof java.util.List); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testNaturalIdLookupProducer() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdDs", + "jdbc:h2:mem:naturaliddb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + Session session = comp.getSessionFactory().openSession(); + Transaction transaction = session.beginTransaction(); + + HibernateTestEntity entity = new HibernateTestEntity(); + entity.setId(1L); + entity.setName("test"); + session.persist(entity); + + transaction.commit(); + session.close(); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setNaturalIdParameters(Map.of("name", "test")); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + HibernateTestEntity result = exchange.getMessage().getBody(HibernateTestEntity.class); + + assertNotNull(result); + assertEquals(1L, result.getId()); + assertEquals("test", result.getName()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testNaturalIdPrefixUriBinding() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdPrefixDs", + "jdbc:h2:mem:naturalidprefixdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = (HibernateEndpoint) comp.createEndpoint( + "hibernate:" + HibernateTestEntity.class.getName() + "?naturalId.name=test"); + + assertEquals(Map.of("name", "test"), endpoint.getNaturalIdParameters()); + + comp.stop(); + } + + @Test + public void testNaturalIdBeanParameter() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdBeanDs", + "jdbc:h2:mem:naturalidbeandb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + context.getRegistry().bind("naturalIdMap", Map.of("name", "test")); + + HibernateEndpoint endpoint = (HibernateEndpoint) comp.createEndpoint( + "hibernate:" + HibernateTestEntity.class.getName() + "?naturalIdParameters=#naturalIdMap"); + + assertEquals(Map.of("name", "test"), endpoint.getNaturalIdParameters()); + + comp.stop(); + } + + @Test + public void testNaturalIdLookupFromMessageHeader() throws Exception { + HibernateComponent comp = createComponent( + "naturalIdHeaderDs", + "jdbc:h2:mem:naturalidheaderdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + Session session = comp.getSessionFactory().openSession(); + Transaction transaction = session.beginTransaction(); + + HibernateTestEntity entity = new HibernateTestEntity(); + entity.setId(1L); + entity.setName("test"); + session.persist(entity); + + transaction.commit(); + session.close(); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setNaturalIdParameters(Map.of("name", "${header.lookupName}")); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + exchange.getMessage().setHeader("lookupName", "test"); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + HibernateTestEntity result = exchange.getMessage().getBody(HibernateTestEntity.class); + + assertNotNull(result); + assertEquals(1L, result.getId()); + assertEquals("test", result.getName()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testSelectionQueryWithFilter() throws Exception { + HibernateComponent comp = createComponent( + "filterDs", + "jdbc:h2:mem:filterdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + Session session = comp.getSessionFactory().openSession(); + Transaction transaction = session.beginTransaction(); + + HibernateTestEntity first = new HibernateTestEntity(); + first.setId(1L); + first.setName("test"); + + HibernateTestEntity second = new HibernateTestEntity(); + second.setId(2L); + second.setName("other"); + + session.persist(first); + session.persist(second); + + transaction.commit(); + session.close(); + + HibernateEndpoint endpoint = new HibernateEndpoint(); + endpoint.setCamelContext(context); + endpoint.setSessionFactory(comp.getSessionFactory()); + endpoint.setEntityClassName(HibernateTestEntity.class.getName()); + endpoint.setSelectionQuery("from HibernateTestEntity"); + endpoint.setFilters(Map.of("nameFilter", Map.of("name", "test"))); + + endpoint.start(); + + Exchange exchange = context.getEndpoint("direct:test").createExchange(); + + try (HibernateProducer producer = new HibernateProducer(endpoint)) { + producer.process(exchange); + } + + java.util.List<?> results = exchange.getMessage().getBody(java.util.List.class); + + assertEquals(1, results.size()); + HibernateTestEntity result = (HibernateTestEntity) results.get(0); + assertEquals("test", result.getName()); + + endpoint.stop(); + comp.stop(); + } + + @Test + public void testFilterPrefixUriBinding() throws Exception { + HibernateComponent comp = createComponent( + "filterPrefixDs", + "jdbc:h2:mem:filterprefixdb;DB_CLOSE_DELAY=-1", + HibernateTestEntity.class); + + HibernateEndpoint endpoint = (HibernateEndpoint) comp.createEndpoint( + "hibernate:" + HibernateTestEntity.class.getName() + + "?selectionQuery=from%20HibernateTestEntity&filter.nameFilter.name=test"); + + assertEquals(Map.of("nameFilter", Map.of("name", "test")), endpoint.getFilters()); + assertEquals("from HibernateTestEntity", endpoint.getSelectionQuery()); + + comp.stop(); + } + + @Test + @SuppressWarnings("unchecked") + public void testTenantIdentifierUsedForSession() throws Exception { + SessionFactory sessionFactory = Mockito.mock(SessionFactory.class); + SessionBuilder sessionBuilder = Mockito.mock(SessionBuilder.class); + Session session = Mockito.mock(Session.class); + Transaction transaction = Mockito.mock(Transaction.class); + SelectionQuery<HibernateTestEntity> query = Mockito.mock(SelectionQuery.class); + + Mockito.when(sessionFactory.withOptions()).thenReturn(sessionBuilder); + Mockito.when(sessionBuilder.tenantIdentifier("tenant1")).thenReturn(sessionBuilder); + Mockito.when(sessionBuilder.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + Mockito.when(session.createSelectionQuery( + "from HibernateTestEntity", HibernateTestEntity.class)).thenReturn(query); + Mockito.when(query.getResultList()).thenReturn(java.util.List.of()); Review Comment: Same here: ```suggestion Mockito.when(query.getResultList()).thenReturn(List.of()); ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
