0

Have found a million posts on this and tried just as many approaches. Fact is I can't find anywhere an example of configuring a Spring app with Hibernate, that has transactions supported OK in Websphere 8(.5).

Here's my spring config:

@Configuration
@ComponentScan(basePackages={"foobar"})
@EnableTransactionManagement // equiv to <tx:annotation-driven/>
@EnableAspectJAutoProxy(proxyTargetClass=true) // equiv to <aop:aspectj-autoproxy/>
public class MySpringConfiguration {

    @Autowired
    private AutowireCapableBeanFactory beanFactory;

    @Bean(name = "dataSource")
    public DataSource dataSource() { 
        try {
            final javax.naming.InitialContext ic = new javax.naming.InitialContext();
            return (javax.sql.DataSource) ic.lookup(FoobarConfiguration.getInstance().getDatasourceJNDIName());
        } catch (final NamingException ne) {
            throw new RuntimeException("Failed to access JNDI lookup using (" + FoobarConfiguration.getInstance().getDatasourceJNDIName() + ")", ne);
        }
    }

    @Bean(name = "sessionFactory")
    public SessionFactory sessionFactory() {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
        builder.scanPackages("foobar.om");

        // builder.setJtaTransactionManager(new WebSphereUowTransactionManager());
        // Didn't work. gave: org.hibernate.TransactionException: Could not register synchronization for container transaction

        Properties props = buildHibernateProperties();
        builder.addProperties(props);

        return builder.buildSessionFactory();
    }

    /**
     * These were taken, with comments, from application-config conversion
     */
    private Properties buildHibernateProperties() {
        Properties props = new Properties();

        // Set the default-schema for Hibernate to use.
        props.setProperty("hibernate.default_schema", "foobar");

        props.setProperty("hibernate.dialect", "org.hibernate.dialect.DB2Dialect");
        props.setProperty("hibernate.hbm2ddl.auto", "validate");

        // Sets the DEBUG Level of the hibernate: SQL generation layer.
        props.setProperty("hibernate.show_sql", "true");

        props.setProperty("hibernate.generate_statistics", "false");

        props.setProperty("hibernate.order_updates", "true");
        props.setProperty("hibernate.order_inserts", "true");

        // Not needed as we have Spring: http://stackoverflow.com/questions/4293098/how-to-integrate-spring-with-hibernate-session-and-transaction-management
        // props.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");

        props.setProperty("hibernate.cache.use_query_cache", "false");
        props.setProperty("hibernate.cache.use_second_level_cache", "false");
        return props;
    }

    @Bean(name = "transactionManager")
    public HibernateTransactionManager transactionManager() {
        return new HibernateTransactionManager(sessionFactory());
    }

    @Bean(name = "persistenceExceptionTranslationPostProcessor")
    public PersistenceExceptionTranslationPostProcessor getExceptionProcessor() {
        return new PersistenceExceptionTranslationPostProcessor();
    }
}

The version as shown works fine in local Jetty environment. It's on deployment to Websphere that an exception is thrown when commence a transaction:

org.hibernate.HibernateException: No CurrentSessionContext configured!

You can see in the config 2 earlier commented-out approaches. The former, setJtaTransactionManager is from the class-level javadoc note on http://docs.spring.io/spring/docs/4.0.2.RELEASE/javadoc-api/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.html. But if I should have something in there then I don't know what it is.

mvn deps:

        <spring-version>4.0.5.RELEASE</spring-version>
        <hibernate-version>4.3.5.Final</hibernate-version>
        ...
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.1</version>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate-version}</version>
            <exclusions>
                <!-- The following has classes (e.g. SystemException) that clashes with 
                    an equivalent in Jetty -->
                <exclusion>
                    <groupId>org.jboss.spec.javax.transaction</groupId>
                    <artifactId>jboss-transaction-api_1.2_spec</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

EDIT 21/07: Stacktrace as requested by James:

org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor 'public foobar.pages.MaintainOpPage(org.apache.wicket.request.mapper.parameter.PageParameters)' and argument ''. An exception has been thrown during construction!
        at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:194)
        at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:76)
        at org.apache.wicket.DefaultMapperContext.newPageInstance(DefaultMapperContext.java:133)
        at org.apache.wicket.core.request.handler.PageProvider.resolvePageInstance(PageProvider.java:268)
        at org.apache.wicket.core.request.handler.PageProvider.getPageInstance(PageProvider.java:166)
        at org.apache.wicket.request.handler.render.PageRenderer.getPage(PageRenderer.java:78)
        at org.apache.wicket.request.handler.render.WebPageRenderer.renderPage(WebPageRenderer.java:100)
        at org.apache.wicket.request.handler.render.WebPageRenderer.respond(WebPageRenderer.java:221)
        at org.apache.wicket.core.request.handler.RenderPageRequestHandler.respond(RenderPageRequestHandler.java:175)
        at org.apache.wicket.request.cycle.RequestCycle$HandlerExecutor.respond(RequestCycle.java:862)
        at org.apache.wicket.request.RequestHandlerStack.execute(RequestHandlerStack.java:64)
        at org.apache.wicket.request.cycle.RequestCycle.execute(RequestCycle.java:261)
        at org.apache.wicket.request.cycle.RequestCycle.processRequest(RequestCycle.java:218)
        at org.apache.wicket.request.cycle.RequestCycle.processRequestAndDetach(RequestCycle.java:289)
        at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:259)
        at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:201)
        at org.apache.wicket.protocol.http.WicketServlet.doGet(WicketServlet.java:137)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1224)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:774)
        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:456)
        at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1032)
        at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3748)
        at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
        at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:962)
        at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
        at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
        at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:283)
        at com.ibm.ws.ssl.channel.impl.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1048)
        at com.ibm.ws.ssl.channel.impl.SSLConnectionLink.readyInboundPostHandshake(SSLConnectionLink.java:716)
        at com.ibm.ws.ssl.channel.impl.SSLConnectionLink$MyHandshakeCompletedCallback.complete(SSLConnectionLink.java:412)
        at com.ibm.ws.ssl.channel.impl.SSLUtils.handleHandshake(SSLUtils.java:1066)
        at com.ibm.ws.ssl.channel.impl.SSLHandshakeIOCallback.complete(SSLHandshakeIOCallback.java:87)
        at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
        at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
        at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
        at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
        at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
        at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
        at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
        at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1814)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:80)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:539)
        at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:171)
        ... 45 more
Caused by: org.hibernate.HibernateException: No CurrentSessionContext configured!
        at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
        at foobar.repository.impl.OpDao.findOp(OpDao.java:43)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
        at java.lang.reflect.Method.invoke(Method.java:613)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        at $Proxy59.findOp(Unknown Source)
        at foobar.service.impl.OpService.generateNewTrn(OpService.java:42)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
        at java.lang.reflect.Method.invoke(Method.java:613)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        at $Proxy62.generateNewTrn(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
        at java.lang.reflect.Method.invoke(Method.java:613)
        at org.apache.wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:435)
        at $Proxy69.generateNewTrn(Unknown Source)
        at foobar.pages.MaintainOpPage.<init>(MaintainOpPage.java:59)
        ... 50 more
Brad M
  • 405
  • 6
  • 17
  • Why do you have to use AspectJ proxying? Are you not working with interfaces? Spring is designed around using interfaces for classes. That's how autowiring works best. If you want a tutorial on how to add Hibernate 4 to an existing Spring project with an explanation of what your configuration options are have a look at the tutorial I wrote [here](http://stackoverflow.com/questions/24422678/minimal-hibernate-4-xml-configuration-with-spring-3-for-annotation-based-transac) however, I only show how to do XML configuration, but you should be able to port it to Java based config. – JamesENL Jul 17 '14 at 04:55
  • Also, you don't have to enable AOP for Hibernate to work, you only need to enable AOP if you want to write custom aspects – JamesENL Jul 17 '14 at 04:56
  • Why do you think that its the WebSphere deployment that is causing problems? Where is that exception thrown? – JamesENL Jul 17 '14 at 05:01
  • @JamesMassey thanks for your comments. We mostly have interfaces but there are a couple of classes without. I don't think that's a major. I guess the AOP dependency you're talking about is via aspectj? We just use for Hibernate/spring proxying of classes. – Brad M Jul 17 '14 at 22:34
  • @JamesMassey The exception is thrown from our DAO layer when trying to access the current session (our service layer classes above this are `@Transactional` at the class level). `... at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012) foobar.repository.impl.NetworkOperatorDao.findNetworkOperator(NetworkOperatorDao.java:48) ... spring proxying calls... org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)`. Works fine in Jetty but not in Websphere, hence my approach. Thanks – Brad M Jul 17 '14 at 22:37
  • @JamesMassey I've removed the aspectj requirement (there was an accidental typing of impl rather than interface). I'm already doing everything you outlined in your first comment. Unfortunately no further along. Cheers – Brad M Jul 21 '14 at 03:24
  • Could you post the full stacktrace in the question please? – JamesENL Jul 21 '14 at 03:25
  • @JamesMassey Added the trace. Changing project to use Hibernate v3 now like another older project we have here, as it works. Will report back. Cheers – Brad M Jul 21 '14 at 03:52

1 Answers1

1

I only had issues when I upgraded from 4.1.0 to 4.3.5. Unless you need 4.3.5 functionality you don't need to downgrade all the way to 3. The 4.3.5 version does work fine in Jetty though. It is only websphere I have issues with. Imagine that.

Eric Winter
  • 960
  • 1
  • 8
  • 17
  • Thanks Eric. I've since tried 4.3.6, 4.3.5 and 4.3.4, none of which work (same `No CurrentSessionContext` error). 4.1 and 4.2 work, so now sticking with 4.2.15.Final. Have you found a bug report open with Hibernate for this? – Brad M Jul 22 '14 at 03:14