davsclaus commented on code in PR #27935: URL: https://github.com/apache/camel/pull/27935#discussion_r4294504382
########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateComponent.java: ########## @@ -0,0 +1,244 @@ +/* + * 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.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.camel.Endpoint; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.DefaultComponent; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.AvailableSettings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Component("hibernate") +public class HibernateComponent extends DefaultComponent { + + private static final Logger LOG = LoggerFactory.getLogger(HibernateComponent.class); + + @Metadata(description = "The Hibernate SessionFactory to use.") + private SessionFactory sessionFactory; + + @Metadata(description = "The DataSource to use for bootstrapping the SessionFactory (bean reference or registry name).") + private Object dataSource; + + private Class<?>[] entityClasses; + + @Metadata(description = "Schema generation action: none, validate, update, create, create-drop, create-only, drop.", + defaultValue = "none") + private String schemaAction = "none"; + + @Metadata(description = "Arbitrary Hibernate configuration properties passthrough map.") + private Map<String, Object> hibernateProperties = new HashMap<>(); + + private boolean sessionFactoryOwned; + private StandardServiceRegistry serviceRegistry; + + public HibernateComponent() { + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + + // 1. Explicitly configured SessionFactory takes precedence (External, unowned) + if (sessionFactory != null) { + sessionFactoryOwned = false; + LOG.info("Using explicitly configured Hibernate SessionFactory (external, unowned)."); + return; + } + + // 2. Try to resolve SessionFactory from Camel registry (External, unowned) + sessionFactory = getCamelContext().getRegistry().findSingleByType(SessionFactory.class); + if (sessionFactory != null) { + sessionFactoryOwned = false; + LOG.info("Reusing existing Hibernate SessionFactory found in Camel registry (external, unowned)."); + return; + } + + // 3. Bootstrap SessionFactory natively (Component-created, owned) + validateSchemaAction(schemaAction); + sessionFactory = createAndBootstrapSessionFactory(); + sessionFactoryOwned = true; + LOG.info("Successfully bootstrapped native Hibernate SessionFactory (component-created, owned)."); + } + + @Override + protected void doStop() throws Exception { + if (sessionFactoryOwned && sessionFactory != null && !sessionFactory.isClosed()) { + LOG.info("Closing component-owned Hibernate SessionFactory."); + sessionFactory.close(); + } + if (serviceRegistry != null) { + StandardServiceRegistryBuilder.destroy(serviceRegistry); + serviceRegistry = null; + } + sessionFactory = null; + sessionFactoryOwned = false; + super.doStop(); + } + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { + HibernateEndpoint endpoint = new HibernateEndpoint(uri, this); + + if (remaining != null && !remaining.isEmpty()) { + endpoint.setEntityClassName(remaining); + } + + setProperties(endpoint, parameters); + endpoint.setSessionFactory(sessionFactory); + + return endpoint; + } + + private void validateSchemaAction(String action) { + + switch (action.toLowerCase()) { Review Comment: The `null` guard was removed in this round, so `setSchemaAction(null)` from Java now fails with an NPE here. `createAndBootstrapSessionFactory()` (line 153) still treats `null` as "none", so the two disagree. Either keep the guard, or treat `null` as "none" here too. ########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateComponent.java: ########## @@ -0,0 +1,244 @@ +/* + * 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.HashMap; +import java.util.Map; + +import javax.sql.DataSource; + +import org.apache.camel.Endpoint; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.annotations.Component; +import org.apache.camel.support.DefaultComponent; +import org.hibernate.SessionFactory; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.AvailableSettings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Component("hibernate") +public class HibernateComponent extends DefaultComponent { + + private static final Logger LOG = LoggerFactory.getLogger(HibernateComponent.class); + + @Metadata(description = "The Hibernate SessionFactory to use.") + private SessionFactory sessionFactory; + + @Metadata(description = "The DataSource to use for bootstrapping the SessionFactory (bean reference or registry name).") + private Object dataSource; + + private Class<?>[] entityClasses; + + @Metadata(description = "Schema generation action: none, validate, update, create, create-drop, create-only, drop.", + defaultValue = "none") Review Comment: Adding `enums = "none,validate,update,create,create-drop,create-only,drop"` here would let the catalog, the YAML schema and the tooling validate the value, and keep the generated docs in sync with `validateSchemaAction` (regen needed). ########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateProducer.java: ########## @@ -0,0 +1,278 @@ +/* + * 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.Expression; +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 final Map<String, Object> naturalIdParameters = new LinkedHashMap<>(); + + public HibernateProducer(HibernateEndpoint endpoint) { + super(endpoint); + this.endpoint = endpoint; + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + Language simple = endpoint.getCamelContext().resolveLanguage("simple"); + + naturalIdParameters.clear(); + if (endpoint.getNaturalIdParameters() != null) { + endpoint.getNaturalIdParameters().forEach((key, value) -> { + if (value instanceof String str) { + naturalIdParameters.put(key, simple.createExpression(str)); + } else { + naturalIdParameters.put(key, value); + } + }); + } + } + + private Map<String, Object> resolveNaturalIdParameters(Exchange exchange, Map<String, Object> headerParameters) { + Map<String, Object> resolved = new LinkedHashMap<>(); + + naturalIdParameters.forEach((key, value) -> { + if (value instanceof Expression expression) { + resolved.put(key, expression.evaluate(exchange, Object.class)); + } else { + resolved.put(key, value); + } + }); + + if (headerParameters != null) { + // Header values are message data and must never be evaluated as Simple expressions. + resolved.putAll(headerParameters); + } + + return resolved; + } + + @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) { Review Comment: `HibernateEndpoint.doStart()` counts the natural-id operation only when the map is non-empty, but this branch is taken whenever it is non-null. An endpoint with an empty `naturalIdParameters` map (for example from a bean) plus `selectionQuery` passes validation, and then runs a natural-id lookup with no keys instead of the query. ```suggestion if (endpoint.getNaturalIdParameters() != null && !endpoint.getNaturalIdParameters().isEmpty()) { ``` ########## components/camel-hibernate/src/main/java/org/apache/camel/component/hibernate/HibernateConsumer.java: ########## @@ -0,0 +1,128 @@ +/* + * 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.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.support.ScheduledPollConsumer; +import org.hibernate.LockMode; +import org.hibernate.Session; +import org.hibernate.Timeouts; +import org.hibernate.Transaction; +import org.hibernate.query.SelectionQuery; + +public class HibernateConsumer extends ScheduledPollConsumer { + + private final HibernateEndpoint endpoint; + + public HibernateConsumer(HibernateEndpoint endpoint, Processor processor) { + super(endpoint, processor); + this.endpoint = endpoint; + } + + @Override + protected int poll() throws Exception { + if (endpoint.getSelectionQuery() == null || endpoint.getSelectionQuery().isBlank()) { Review Comment: Endpoint validation accepts `mutationQuery`, `naturalIdParameters` or `statelessOperation` alone, so a consumer endpoint configured with one of those starts fine. It then throws this `IllegalArgumentException` on every poll, which only shows up as a repeated WARN. Could the check move to the consumer's `doStart()`, so a misconfigured route fails at startup? ```java @Override protected void doStart() throws Exception { if (endpoint.getSelectionQuery() == null || endpoint.getSelectionQuery().isBlank()) { throw new IllegalArgumentException("Hibernate consumer requires selectionQuery"); } super.doStart(); } ``` -- 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]
