org.springframework.transaction.CannotCreateTransactionException:无法打开Hibernate Session进行事务处理

时间:2017-04-08 17:29:35

标签: java spring hibernate session transactions

错误日志:

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.372 sec <<< FAILURE!
testCRUDCategory(net.kzn.shoppingbackend.test.CategoryTestCase)  Time elapsed: 0.124 sec  <<< ERROR!
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.$Proxy32.add(Unknown Source)

HibernateConfig.java

@Configuration
@ComponentScan(basePackages={"net.kzn.shoppingbackend.dto"})
@EnableTransactionManagement
public class HibernateConfig {

    // Change the below based on the DBMS you choose
    private final static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/onlineshopping";
    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("net.kzn.shoppingbackend.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");


        return properties;
    }

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


}

测试类 CategoryTestCase.java

public class CategoryTestCase {

    private static AnnotationConfigApplicationContext context;


    private static CategoryDAO categoryDAO;


    private Category category;


    @BeforeClass
    public static void init() {
        context = new AnnotationConfigApplicationContext();
        context.scan("net.kzn.shoppingbackend");
        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));


    }
}

为什么我得到无法打开Hibernate会话进行交易;嵌套异常,似乎一切都很好,为什么这个错误我得到 你也可以检查一下git Hub代码同样的问题,请帮我解决这个问题 https://github.com/rustyamigo/online-shopping

1 个答案:

答案 0 :(得分:0)

我克隆了你的项目并找到Connection is broken: "java.net.ConnectException: Connection refused: localhost" [90067-194]),你似乎没有启动H2服务器。根据您的URL,您正在使用tcp连接,即必须首先启动服务器。

我有一些谷歌搜索,发现你可以通过两种方式解决它:

你需要一个启动服务器的java master程序,如下所示: org.h2.tools.Server.createTcpServer().start(); 例如: 在你的测试班 - &gt; ProductTestCase.java

@BeforeClass
public static void init() throws Exception {
    org.h2.tools.Server.createTcpServer().start();
    context = new AnnotationConfigApplicationContext();
    context.scan("net.kzn.shoppingbackend");
    context.refresh();
    productDAO = (ProductDAO)context.getBean("productDAO");
}

或者您可以在连接尝试之前手动启动它,如下所示: java -cp h2*.jar org.h2.tools.Server