2014-10-31 2 views
6

나쁜 영어로 유감스럽게 생각합니다. 내 프로젝트는 예외 No CurrentSessionContext configured가 발생, spring-boot 1.1.8 시작, 나는 몇 가지 검색이 문제를 해결할 수있는 재산 <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>을 추가 할 수 있지만CurrentSessionContext가 구성되지 않았습니다.

방법 자바 클래스를 사용하여이 속성을 config (설정)하기를 했습니까?

업데이트 : SessionFactory를 정의하기 위해 Hibernate4.x Way으로 변경되었지만 여전히 동일한 오류가 발생했습니다. 제발 도와주세요! 여기

사용 java 1.8speing boot 1.1.8

내 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> 

내 서비스 및 컨트롤러는

@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(); 
    } 
} 
,536,913 63,210

업데이트 : 최대 절전 모드의 잘못

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[email protected]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) 
+0

아니요. 문제가 해결되지 않으면 문제가 악화됩니다.'HibernateJpaSessionFactoryBean'을 사용하여 컨텍스트 내에서 SessionFactory를 얻으려면'SessionFactory' (왜 슬프지만 왜 안 좋은지)가 필요하다면, 직접 래핑하지 말고 주입하십시오. 구성/응용 프로그램 클래스를 게시하십시오. 또한'UserServiceImpl'에'@Service'와'@Transaction'으로 주석을 붙일 것으로 예상됩니다. 트랜잭션이 없기 때문입니다. –

+0

@ M.Deinum 선생님, 감사드립니다. 네, 실제로 SessionFactory를 사용하려고합니다. 왜냐하면 나는 절전 기준을 사용하기로 결정했기 때문입니다. – Teifi

+0

JPA는 또한 JPA2 기준으로 criterias를 가지고 있으며 simpel 쿼리가 단지 쿼리를 사용하기 때문에 실제로는 JPA2를 사용하는데주의를 기울여야합니다. –

답변

21

귀하의 구성 및 사용 : 여기 내 전체 스택 추적입니다. 당신은 Spring과 더 나은 Spring Boot를 사용하고 있습니다.하지만 게시 한 내용은 이러한 프레임 워크를 사용하지 않으려 고 노력하고 시도해 보려고 노력합니다. 나는 Spring Boot를 사용하여 당신에게 필요한 것들을 설정하도록 강력하게 제안한다.

먼저 HibernateUtils을 삭제하고 깊이 묻어서 다시 보지 마십시오. 또한 봄 부팅으로 AppConfig을 삭제하고 DataSource을 처리 할 수 ​​있습니다.

다음 src/main/resources 디렉토리에 application.properties이라는 파일을 만들고 다음 내용을 입력하십시오.

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

그러면 자동으로 DataSource이 자동으로 구성됩니다. 당신은 당신이 제공 한 URL에서 추론되는 드라이버를 필요로하지 않습니다. 그런 다음 JPA를 구성하기 위해 다음 등록 정보를 추가하십시오.

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

더 많은 설정과 속성의 전 속성에 대한 Spring Boot Reference Guide의 읽기이 comprehensive list을 확인하시기 바랍니다.

다음으로 WebApplicationStarterHibernateJpaSessionFactoryBean을 추가하면 생성 된 JPA EntityManagerFactorySessionFactory으로 표시됩니다.

@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(); 
    } 
} 

그럼 그냥 @AutowireSessionFactory 당신의 UserServiceImpl에.

@Service 
@Transactional 
public class UserServiceImpl implements UserService { 

    @Autowired 
    private SessionFactory sessionFactory; 

} 

이제 SessionFactory을 사용할 수 있습니다.

+0

오류가 발생하면서 업데이 트되었습니다. – Teifi

+0

흥미로운 것은, 어떤 이유로, 필요한 인터페이스를 구현하지 않는 프록시가 생성되고 있다는 것입니다. Spring Boot에 의존하는 대신 커스텀 설정을 가지고 있습니까? 아, 당신은 사소한 문제에 빠져 있습니다. 두려운 것 같습니다. 봄은 일반적으로 최대 절전 모드 4.3 이하에서 작동하도록 업데이트되었지만,이 클래스는 내가 추측 한 것입니다. 나는 해답을 얻을 수있는 해결책에 대한 해답을 업데이트했다. –

+0

더 이상 사용자 지정 구성이 없습니다. 일단 내가'@Bean HibernateJpaSessionFactoryBean'을 사용하면 좌절감을 느낍니다.이 오류가 나왔습니다. 나는 머리카락을 긁어 내고 싶습니다! 다른 데이터 소스를 설정하고 싶습니다. 하나는 읽는 것이고 다른 하나는 쓰는 것이지만, 그 안식처가 시작됩니다. – Teifi