11

sorry for bad English. I get my project started with spring-boot 1.1.8, Encountered Exception No CurrentSessionContext configured, then I did some search, add property <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property> could solve this problem, but

how to config this property using java class?

update: I changed to the Hibernate4.x Way to define SessionFactory but still got the same error, please help!

Use java 1.8 and speing boot 1.1.8

here is my pom.xml

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <main.basedir>${basedir}/../..</main.basedir>
        <m2eclipse.wtp.contextRoot>../</m2eclipse.wtp.contextRoot>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.1.8.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

here is my Service and Controller

@AutoWried
SessionFactory sessionFactory;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    public boolean isEmailExist(String email) {
        Session session = sessionFactory.openSession();
        // if I use getCurrentSession(), I will got the No Session found for current thread
        //Session session = sessionFactory.getCurrentSession();
        Criteria c = UserCriteria.isEmailExisting(session, email);
        List<UserInfo> usrs = c.list();
        session.close();
        if (0 == usrs.size() || usrs.isEmpty())
            return false;
        return true;
    }
}

@Controller
public class UserRegisterController {
    @Autowired
    UserService userService;

    @RequestMapping("/doRegist")
    public void doRegister(HttpServletRequest request,
            HttpServletResponse response) {
        String usrEmail = request.getParameter("email");
        boolean exist = userService.isEmailExist(session, usrEmail);
        //todo
    }
}

WebApplicatoinStarter.java

@Configuration
@EnableAutoConfiguration
@ComponentScan("com.mytest")
public class WebApplicationStarter extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder application) {
        return application.sources(WebApplicationStarter.class);
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = SpringApplication.run(WebApplicationStarter.class, args);
    }

    @Bean
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
        return hemf.getSessionFactory();
    }
}

update: here is my full stack trace:

2014-11-01 08:41:11.736  INFO 3312 --- [           main] com.hotsoft.WebApplicationStarter        : Starting WebApplicationStarter on zblqmc with PID 3312 (D:\x51\p2\target\classes started by lzzafll in D:\x51\p2)
2014-11-01 08:41:11.814  INFO 3312 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@442675e1: startup date [Sat Nov 01 08:41:11 CST 2014]; root of context hierarchy
2014-11-01 08:41:13.047  INFO 3312 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2014-11-01 08:41:14.009  INFO 3312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$dd4f2c7a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-11-01 08:41:14.041  INFO 3312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionAttributeSource' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-11-01 08:41:14.056  INFO 3312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'transactionInterceptor' of type [class org.springframework.transaction.interceptor.TransactionInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-11-01 08:41:14.072  INFO 3312 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-11-01 08:41:14.647  INFO 3312 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-11-01 08:41:14.928  INFO 3312 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-11-01 08:41:14.928  INFO 3312 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.55
2014-11-01 08:41:15.755  INFO 3312 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-11-01 08:41:15.771  INFO 3312 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3957 ms
2014-11-01 08:41:16.427  INFO 3312 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-11-01 08:41:16.427  INFO 3312 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-11-01 08:41:17.534  INFO 3312 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2014-11-01 08:41:17.550  INFO 3312 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2014-11-01 08:41:17.660  INFO 3312 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.6.Final}
2014-11-01 08:41:17.660  INFO 3312 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2014-11-01 08:41:17.660  INFO 3312 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2014-11-01 08:41:17.910  INFO 3312 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2014-11-01 08:41:18.050  INFO 3312 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2014-11-01 08:41:18.206  INFO 3312 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2014-11-01 08:41:18.861  INFO 3312 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-11-01 08:41:19.047  INFO 3312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.hotsoft.web.UserRegisterController.hello(java.util.Map<java.lang.String, java.lang.Object>)
2014-11-01 08:41:19.047  INFO 3312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/doRegist],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void com.hotsoft.web.UserRegisterController.doRegister(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2014-11-01 08:41:19.063  INFO 3312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2014-11-01 08:41:19.063  INFO 3312 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2014-11-01 08:41:19.078  INFO 3312 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-11-01 08:41:19.078  INFO 3312 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-11-01 08:41:19.413  INFO 3312 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2014-11-01 08:41:19.554  INFO 3312 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080/http
2014-11-01 08:41:19.569  INFO 3312 --- [           main] com.hotsoft.WebApplicationStarter        : Started WebApplicationStarter in 8.551 seconds (JVM running for 9.276)
2014-11-01 08:41:32.754  INFO 3312 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2014-11-01 08:41:32.754  INFO 3312 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2014-11-01 08:41:32.786  INFO 3312 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 32 ms
2014-11-01 08:41:39.988 ERROR 3312 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No CurrentSessionContext configured!] with root cause

org.hibernate.HibernateException: No CurrentSessionContext configured!
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1012)
    at com.hotsoft.web.UserRegisterController.doRegister(UserRegisterController.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1695)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Simulant
  • 19,190
  • 8
  • 63
  • 98
Teifi
  • 713
  • 2
  • 12
  • 20
  • No that doesn't solve the problem it will make it even worse. If you need a `SessionFactory` (not sure why but alas) use the `HibernateJpaSessionFactoryBean` to get one in your context, then just inject that instead of unwrapping yourself. Post your configuration / application class. Also I would expect your `UserServiceImpl` to be annotated with `@Service` and `@Transactional` as now there is no transaction. – M. Deinum Oct 31 '14 at 07:23
  • @M.Deinum Thank you sir and thanks to your expect! yes i indeed intend to use `SessionFactory` because I decide use hibernate criteria. – Teifi Oct 31 '14 at 07:35
  • JPA also has criterias (as of JPA2) and you should really take care in using those, for simpel queries just use a query. – M. Deinum Oct 31 '14 at 07:51
  • @M.Deinum sir am updated my question, could u give me a hand? – Teifi Oct 31 '14 at 08:32
  • Don't construct your own datasource. Spring Boot does that. Just add the properties to your `application.properties`. Also don't use the util class use Spring. You are trying very hard to NOT use Spring, Spring Boot etc. you are doing everything to work around it. – M. Deinum Oct 31 '14 at 08:35
  • @M.Deinum at the first time, i put the properties to `application.properties` but got error `@Autowried SessionFactory sessionFactory` seems doesn't work. so i tried above, how do i get ride of util and use spring? – Teifi Oct 31 '14 at 08:46

2 Answers2

29

Your configuration and usage of hibernate is wrong. You are using Spring and even better Spring Boot, however what you posted tries very hard not to use those frameworks and tries to work around them. I strongly suggest using Spring Boot and let that configure the things for you.

First delete your HibernateUtils, burry it deep and never look at it again. You can also delete your AppConfig as Spring Boot can and will take care of the DataSource.

Next create a file called application.properties in your src/main/resources directory and put the following content in there.

spring.datasource.url=jdbc:mysql://localhost/mysql
spring.datasource.username=root
spring.datasource.password=

This will automatically configure a DataSource for you. You don't need the driver as that is deduced from the url you provide. Next add the following properties to configure JPA.

spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

For more settings and properties I suggest a read of the Spring Boot Reference Guide for the properties check this comprehensive list.

Next in your WebApplicationStarter add the HibernateJpaSessionFactoryBean to expose the created JPA EntityManagerFactory as a SessionFactory.

@Configuration
@EnableAutoConfiguration
@ComponentScan("com.mytest")
public class WebApplicationStarter extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplicationStarter.class);
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = SpringApplication.run(WebApplicationStarter.class, args);
    }

    @Bean
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
        return hemf.getSessionFactory();
    }
}

Then just @Autowire the SessionFactory into your UserServiceImpl.

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SessionFactory sessionFactory;

}

Now you can just use the SessionFactory.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • Hmm interesting, for some reason a proxy is getting created which doesn't implement the required interfaces. Do you have more custom configuration instead of relying on Spring Boot? Ah, you are running into a minor issue here I'm afraid... Although Spring has generally been updated to work with hibernate 4.3 and lower, this class was an oversight I guess. I updated the answer to a solution that should work. – M. Deinum Oct 31 '14 at 09:09
  • absolutely not have any more custom configuration. i'm frustrated, once i use `@Bean HibernateJpaSessionFactoryBean` this error came out, i want to scrab my hair out! I want to config another datasource, one is to read and another one is to write, but that haven begin. – Teifi Oct 31 '14 at 10:48
  • I created an [issue](https://jira.spring.io/browse/SPR-12401) for this . Meanwhile to modified answer should work. – M. Deinum Oct 31 '14 at 11:15
  • Thank you sir, you must be a good father! Should I restart my project use an older spring release? – Teifi Oct 31 '14 at 11:33
  • No, as I stated the code in my answer (as I modified it) should work, it doesn't use the `HibernateJpaSessionFactoryBean` any more. The issue will be resolved in the next fix (4.1.2 and 4.0.8) for Spring. – M. Deinum Oct 31 '14 at 12:04
  • dear sir, unfortunately can't vote you Five. as use the `@Bean public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf)`, the `proxy error` doesn't come again, but still the `No CurrentSessionContext configured` exception. anyway Thank you very much. – Teifi Oct 31 '14 at 12:33
  • Do you have a `hibernate.properties` or `hibernate.cfg.xml` file by any chance? Also can you post the full stacktrace? You still must be using another instance/setup then I posted as Spring itself sets the current session context class. – M. Deinum Oct 31 '14 at 12:39
  • Am put my all project structures, maybe this caused by `eclipse` or `maven`? – Teifi Oct 31 '14 at 13:00
  • That shouldn't make difference. Post the full stacktrace. – M. Deinum Oct 31 '14 at 13:02
  • Good morning sir, if you have time, please look at the update, thanks – Teifi Nov 01 '14 at 01:25
  • Why are you even using the `SessionFactory` in your controller looks like that code is still there... As I stated delete the util class. – M. Deinum Nov 02 '14 at 16:17
  • I've just forgotten fix the question's code, i did remove `HibernateUtils.java` and use `@Autowrie SessionFactory sessionFactory` as you suggested at my project. – Teifi Nov 03 '14 at 00:45
  • As I stated you shouldn't be messing around with a session in your controller. That belongs in the service, you will also run into problems now due to not having a transaction. – M. Deinum Nov 03 '14 at 06:34
  • This is getting me a session but the log contains a line saying - `Invocation of destroy method failed on bean with name 'entityManagerFactory': java.lang.IllegalStateException: EntityManagerFactory is closed` – Rajeev Ranjan Oct 23 '17 at 13:58
5

I got this error because I had

sessionFactory.getCurrentSession();

when I changed it to

sessionFactory.openSession();

it worked fine.

parsecer
  • 4,758
  • 13
  • 71
  • 140