【发布时间】:2018-05-01 14:35:12
【问题描述】:
您好,我有一个使用 Hibernate 作为 ORM 的 Spring Boot 应用程序,用于从 sybase 数据库中获取数据。
我有一个非常基本的设置,它在嵌入式服务器上运行良好。 我使用此以下站点生成战争并将其成功部署到本地 tomcat 服务器。 https://www.mkyong.com/spring-boot/spring-boot-deploy-war-file-to-tomcat/.
我能够通过覆盖 TOMEE 持久性设置将应用程序部署到 TOMEE 服务器 CATALINA_OPTS=-javax.persistence.provider=org.hibernate.ejb.HibernatePersistence abd 将所需的休眠 jars 放在 TOMEE/lib 中。
问题是当我尝试访问数据时,DAO 中的请求调用 sessionfactory.getcurrentsession() 我收到以下错误:
org.hibernate.HibernateException: Could not obtain transaction-synchronized
Session for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
我正在使用 Spring Boot:1.3.0 TOMEE 1.7.4
请不要评判我的编码,因为这只是一个 sn-p 和我的应用程序配置
Application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/netgloo_blog
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.properties.hibernate.dialect =
org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate4.SpringSessionContext
我的主要应用程序
@SpringBootApplication
public class SpringBootWebApplication extends
SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(SpringBootWebApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
}
控制器
@Controller
public class WelcomeController {
@Autowired
UserService service
@RequestMapping("/authenticate")
public String authenticate(httpServletRequest req, HtttpServletResponse res)
{
return service.authenticate(req.getParameter("userId"));
}
}
服务
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserManager userManager
@override
public String authenticate(String userId)
{
return userManager.authenticate(userId);
}
}
额外的管理层
@Service
@Transactional
public class UserManagerImpl implements UserManager{
@Autowired
UserDao userDao
@override
public String authenticate(String userId)
{
User user = userDao.CheckUserIsPresentInDB(userId);
if(user != null){
return "success";
}
}
}
DAO 层
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
SessionFactory sessionFactory
@override
public User authenticate(String userId)
{
Criteria criteria = sessionFactory.getCurrentSession().createCriteria;
----
}
}
应用程序在我的本地 Tomcat 7 服务器上运行良好 但在 TOMEE 服务器上获取交易时出错。
我是否需要对代码或 TOMEE 服务器进行任何更改? 请帮忙
【问题讨论】:
-
我已经通过删除 bean 解决了这个问题 @Bean public HibernateJpaSessionFactoryBean sessionFactory() { return new HibernateJpaSessionFactoryBean();并自动装配持久性上下文作为实体管理器我然后使用 entityManager.unWrap() 从 entityManager 解压底层 sessionFactory
标签: hibernate spring-boot apache-tomee