当前位置: 首页 > 知识库问答 >
问题:

无法创建事务异常,无法打开Hibernate会话进行交易

巩俊远
2023-03-14

HibernateConfig

@Configuration
@ComponentScan(basePackages = { "com.app.EcommerceBackend.dto" })
@EnableTransactionManagement
public class HibernateConfig {

    // Change the below based on the DBMS you choose
    private final static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/ecommerce";
    private final static String DATABASE_DRIVER = "org.h2.Driver";
    private final static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect";
    private final static String DATABASE_USERNAME = "sa";
    private final static String DATABASE_PASSWORD = "";

    // dataSource bean will be available
    @Bean
    public DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();

        // Providing the database connection information
        dataSource.setDriverClassName(DATABASE_DRIVER);
        dataSource.setUrl(DATABASE_URL);
        dataSource.setUsername(DATABASE_USERNAME);
        dataSource.setPassword(DATABASE_PASSWORD);

        return dataSource;
    }
    // sessionFactory bean will be available
    @Bean
    public SessionFactory getSessionFactory(DataSource dataSource) {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
        builder.addProperties(getHibernateProperties());
        builder.scanPackages("com.app.EcommerceBackend.dto");
        return builder.buildSessionFactory();
    }

    // All the hibernate properties will be returned in this method
    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", DATABASE_DIALECT);
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        // properties.put("hibernate.hbm2ddl.auto", "create");
        return properties;
    }

    // transactionManager bean
    @Bean
    public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
        return transactionManager;
    }
}

CategoryDAOImpl

@Repository("categoryDAO")
@Transactional
public class CategoryDAOImpl implements CategoryDAO {

    @Autowired
    private SessionFactory sessionFactory;
    private static List<Category> categories = new ArrayList<>();

    static {
        Category category = new Category();
        // Add First Element
        category.setId(1);
        category.setName("Television");
        category.setDescription("this is some desc for television");
        category.setImageURL("img1.jpg");
        categories.add(category);

        // Add Second Element
        category = new Category();
        category.setId(2);
        category.setName("Mobile");
        category.setDescription("this is some desc for Mobile");
        category.setImageURL("img2.jpg");
        categories.add(category);

        // Add Third Element
        category = new Category();
        category.setId(3);
        category.setName("Laptop");
        category.setDescription("this is some desc for Laptop");
        category.setImageURL("img3.jpg");
        categories.add(category);
    }

    @Override
    public List<Category> list() {
        return categories;

    }

    @Override
    public Category get(int id) {
        for (Category category : categories) {
            if (category.getId() == id)
                return category;
        }
        return null;
    }

    @Override
    public boolean add(Category category) {
        // add the category to the databse table
        try {
            sessionFactory.getCurrentSession().persist(category);
            return true;
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

类别

@Entity
public class Category implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String description;

    @Column(name = "image_url")
    private String imageURL;

    @Column(name = "is_active")
    private boolean active = true;

    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + ", description=" + description + ", imageURL=" + imageURL
                + ", active=" + active + "]";
    }
}

类别测试类

public class CategoryTestCase {

    private static AnnotationConfigApplicationContext context;

    private static CategoryDAO categoryDAO;

    private Category category;

    @BeforeClass
    public static void init() throws Exception {
        org.h2.tools.Server.createTcpServer().start();
        context = new AnnotationConfigApplicationContext();
        context.scan("com.app.EcommerceBackend");
        context.refresh();
        categoryDAO = (CategoryDAO) context.getBean("categoryDAO");
    }

    @Test
    public void testAddCategory() {

        category = new Category();

        category.setName("Laptop");
        category.setDescription("This is some description for laptop!");
        category.setImageURL("CAT_105.png");

        assertEquals("Successfully added a category inside the table!", true, categoryDAO.add(category));

    }
}

获取此错误

org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy29.add(Unknown Source)
    at com.app.EcommerceBackend.test.CategoryTestCase.testAddCategory(CategoryTestCase.java:40)

为什么我得到嵌套异常

无法打开事务的Hibernate会话

似乎一切都很好,为什么会出现这个错误?

您也可以检查github代码

共有1个答案

宿嘉
2023-03-14

默认情况下,事务管理器bean的名称是transactionManager,因此将返回HibernateTransactionManager的方法重命名为transaction manager

 类似资料:
  • 错误日志: 冬眠图。JAVA 测试类CategoryTestCase。JAVA 为什么我无法为事务打开Hibernate会话;嵌套异常,似乎一切都很好,为什么我得到这个错误你也可以检查git Hub代码它的相同问题,请帮助我解决这个问题https://github.com/rustyamigo/online-shopping

  • 我不熟悉SpringMVC和Hibernate。尝试使用SpringMVC(4.0.3)、Hibernate(4.3.5)和MySQL作为后端创建一个测试web应用程序。 连接到DB没有问题,因为我尝试使用简单的JDBC连接语句从示例testJavaClass中的同一个DB中获取数据,并且能够获取记录。 错误日志: 这是我的pom。xml: Eclipse中的项目结构: servlet上下文。xm

  • Spring MVC+Hibernate、JavaConfig WebAppConfig: 用户 HTTP状态500-请求处理失败;嵌套异常为org.springframework.transaction.CanNotCreateTransactionException:无法打开事务的Hibernate会话;嵌套异常为java.lang.NoClassDefoundError:org/hibern

  • 有关您编写的代码问题的问题必须描述特定问题-并且在问题本身中包含有效代码以重现它。有关指导,请参阅SSCCE. org。 在我的应用程序中,我有一个模块,用于在数据库中搜索用户并在jsp内的表中显示他们的信息。我只是在应用程序中设置了Spring Security性。我能够从登录页面连接到数据库,尽管出于某种原因,DAO的CRUD操作(在本例中是搜索)都不起作用。 谢谢,如果我能提供更多信息,请告

  • org.openqa.selenium.SessionNotCreatedException:无法创建新会话。(原始错误:命令失败:C:\Windows\system32\cmd.exe/s/C“C:\Program Files(x86)\Android\Android sdk\platform tools\adb.exe”-s 69c7aa170104安装“C:\Program Files(x8

  • 我有一个运行完整的Spring MVC应用程序,运行Spring Security,但每当服务器有一段时间不活动,有人试图登录时,我就会出现以下错误: HTTP状态500-请求处理失败;嵌套的异常是org。springframework。交易CannotCreateTransactionException:无法为事务打开Hibernate会话;嵌套的异常是org。冬眠TransactionExce