Я новичок в Spring и Hibernate. Я создаю приложение Spring, которое извлекает данные из базы данных и передает их в формате json.
Всякий раз, когда я запускаю приложение, я получаю сообщение Не удалось получить сеанс с синхронизацией транзакций для текущего потока . Если я добавлю настройки гибернации в файл springconfig.xml, приложение будет работать нормально. Если я храню их отдельно, я получаю ошибку ниже.
Ниже мой Stacktrace
SEVERE: Servlet.service() for servlet [port] in context with path [/port] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:143)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:496)
at com.port.domain.dao.DomainDAOImpl.getDomains(DomainDAOImpl.java:39)
at com.port.domain.service.DomainServiceImpl.getDomains(DomainServiceImpl.java:21)
at com.port.domain.controller.DomainRestController.getDomains(DomainRestController.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Я попробовал ответ, предоставленный itachi по этой ссылке Spring Hibernate - Не удалось получить сеанс с синхронизацией транзакций для текущего потока . Но, кажется, это обходной путь. Сессия не будет закрыта автоматически. Ниже мой код
Класс My Entity (DomainList.java):
package com.port.domain.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Entity
@Table(name="domainlist")
@Component
public class DomainList {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="domainID")
private int domainID;
@Column(name="domainName")
private String domainName;
@Column(name="currentPrice")
private float currentPrice;
public int getDomainID() {
return domainID;
}
public void setDomainID(int domainID) {
this.domainID = domainID;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public float getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(float currentPrice) {
this.currentPrice = currentPrice;
}
@Override
public String toString() {
return "DomainList [domainID=" + domainID + ", domainName=" + domainName + ", currentPrice=" + currentPrice + "]";
}
}
Мой RestContoller (DomainRestComtroller.java):
package com.port.domain.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.port.domain.model.DomainList;
import com.port.domain.service.DomainService;
@RestController
public class DomainRestController {
@Autowired
private DomainService domainService;
@RequestMapping(value="/getDomains", method=RequestMethod.GET, headers="Accept=application/json")
public List<DomainList> getDomains() {
List<DomainList> domainList = domainService.getDomains();
return domainList ;
}
}
Мой класс обслуживания (DomainServiceImpl.java):
package com.port.domain.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.port.domain.dao.DomainDAO;
import com.port.domain.model.DomainList;
@Service
public class DomainServiceImpl implements DomainService {
@Autowired
private DomainDAO domainDAO;
@Override
@Transactional
public List<DomainList> getDomains() {
return domainDAO.getDomains();
}
}
Мой класс DAO (DomainDAOImpl.java):
package com.port.domain.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.port.domain.model.DomainList;
@Repository
public class DomainDAOImpl implements DomainDAO {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<DomainList> getDomains() {
Session currentSession = sessionFactory.getCurrentSession();
Query<DomainList> theQuery =
currentSession.createQuery("from DomainList", DomainList.class);
List<DomainList> Domains = theQuery.getResultList();
for (DomainList domain : Domains)
System.out.println(domain.toString());
return Domains;
}
}
My springconfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config />
<mvc:annotation-driven/>
<!-- For the Stereotype annotations to work -->
<context:component-scan
base-package="com.port.domain.controller" />
<context:component-scan
base-package="com.port.domain.dao" />
<context:component-scan
base-package="com.port.domain.model" />
<context:component-scan
base-package="com.port.domain.service" />
Мой hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="myDataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/port" />
<property name="user" value="username" />
<property name="password" value="password" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan"
value="com.port.domain.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager"/>
<mvc:resources location="/resources/"
mapping="/resources/**"></mvc:resources>
</beans>
Мой web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>SpringMvcRestHibernate</display-name>
<servlet>
<servlet-name>port</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springconfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>port</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Database configuration file -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/hibernate.cfg.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
В соответствии с моим пониманием, это должно работать нормально после просмотра многих примеров такого рода. Но я не понимаю, почему я получаю ошибку.