gpt4 book ai didi

java - 使用@Transactional但仍然得到: Could not obtain transaction-synchronized Session for current thread

转载 作者:行者123 更新时间:2023-12-01 18:29:29 24 4
gpt4 key购买 nike

我已经出现此错误好几天了,查看我的代码:

错误代码:

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:136)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:496)
com.test.dao.DoctorDAOImpl.getDoctor(DoctorDAOImpl.java:34)
com.test.service.MainServiceImpl.getDoctor(MainServiceImpl.java:39)
com.test.controller.MainController.showMain(MainController.java:23)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:566)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

配置.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test")
@PropertySource({"classpath:persistence-mysql.properties"})
public class Config {
@Autowired
private Environment env;

private Logger logger = Logger.getLogger(getClass().getName());

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
System.out.println("\ntesting "+env.getProperty("jdbc.url")+"\n\n");
return viewResolver;
}

@Bean
public DataSource myDataSource() {

// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();

// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}

// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));

// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));

// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));

return myDataSource;
}

private Properties getHibernateProperties() {

// set hibernate properties
Properties props = new Properties();

props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));

return props;
}


// need a helper method
// read environment property and convert to int

private int getIntProperty(String propName) {

String propVal = env.getProperty(propName);

// now convert to int
int intPropVal = Integer.parseInt(propVal);

return intPropVal;
}

@Bean
public LocalSessionFactoryBean sessionFactory(){

// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());

return sessionFactory;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {

// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);

return txManager;
}
}

MainServiceImpl.java

package com.test.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.test.dao.DoctorDAO;
import com.test.dao.PatientDAO;
import com.test.entity.Doctor;
import com.test.entity.Patient;

@Service
public class MainServiceImpl implements MainService {

@Autowired
private PatientDAO patientDao;

@Autowired
private DoctorDAO doctorDao;

@Override
@Transactional
public List<Patient> getPatients() {
System.out.println("inside service: getPatients method");
return patientDao.getPatients();
}

@Override
@Transactional
public Patient getPatient(int theId) {
return patientDao.getPatient(theId);
}

@Override
@Transactional
public Doctor getDoctor(int theId) {
return doctorDao.getDoctor(theId);
}

@Override
@Transactional
public void addPatient(Patient thePatient) {
patientDao.savePatient(thePatient);
}

@Override
@Transactional
public void addDoctor(Doctor theDoctor) {
doctorDao.saveDoctor(theDoctor);
}

@Override
@Transactional
public void deletePatient(int theId) {
patientDao.deletePatient(theId);
}

}

MainController.java

package com.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.entity.Doctor;
import com.test.service.MainService;

@Controller
@RequestMapping("main")
public class MainController {

@Autowired
private MainService service;

@RequestMapping("/")
@Transactional
public String showMain(Model theModel) {
System.out.println("inside show Main method");
Doctor theDoctor = service.getDoctor(1);
// List<Patient> thePatients = service.getPatients();
// System.out.println(thePatients);
theModel.addAttribute("doctor", theDoctor);
return "main";
}
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.practice</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>test</name>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.0.RELEASE</springsecurity.version>

<hibernate.version>5.4.1.Final</hibernate.version>

<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

</properties>

<dependencies>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>

<!-- Spring orm and tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>

<!-- Spring Security Support -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<!-- Spring Security JSP tag support -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>

<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>

<!-- Servlet, JSP and JSTL support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>


<!-- to compensate for java 9+ not including jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>

<build>
<finalName>test</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add maven coordinates: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

DoctorDAOImpl.java

package com.test.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.stereotype.Repository;

import com.test.entity.Doctor;
import com.test.entity.Patient;

@Repository
public class DoctorDAOImpl implements DoctorDAO {

@Autowired
private SessionFactory sessionFactory;

@Override
public List<Patient> getPatients(int theId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query<Patient> theQuery = session.createQuery("from Patient p where p.doctor.id=:doctorId");
theQuery.setParameter("doctorId", theId);
List<Patient> result = theQuery.getResultList();
session.getTransaction().commit();
return result;
}

@Override
public Doctor getDoctor(int theId) {
Session session = sessionFactory.getCurrentSession();
return session.get(Doctor.class, theId);
}

@Override
public void saveDoctor(Doctor theDoctor) {
Session session = sessionFactory.getCurrentSession();
session.save(theDoctor);
}

}

PatientDAOImpl.java

package com.test.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.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.test.entity.Patient;

@Repository
public class PatientDAOImpl implements PatientDAO {

@Autowired
private SessionFactory sessionFactory;

@Override
public List<Patient> getPatients() {
System.out.println("inside repository: getPatients method");
Session session = sessionFactory.getCurrentSession();
Query<Patient> theQuery = session.createQuery("from Patient",Patient.class);
return theQuery.getResultList();
}

@Override
public void savePatient(Patient thePatient) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(thePatient);
}

@Override
public Patient getPatient(int theId) {
Session session = sessionFactory.getCurrentSession();
return session.get(Patient.class,theId);
}

@Override
public void deletePatient(int theId) {
Session session = sessionFactory.getCurrentSession();
Query theQuery = session.createQuery("delete from Patient where id=:patientId");
theQuery.setParameter("patientId", theId);
theQuery.executeUpdate();
}

}

I'm sorry that I dumped all my code here, but this is the best I could do.

最佳答案

请在发布问题之前考虑使用搜索,因为这个问题已在 Stack Overflow 上被多次询问。除了@m-deinum 的评论(支持他!)你会找到答案,例如hereherehere :请添加@EnableTransactionManagement注释。

关于java - 使用@Transactional但仍然得到: Could not obtain transaction-synchronized Session for current thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60186418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com