org.h2.jdbc.JdbcSQLException:连接断开:“java.net.ConnectException:连接被拒绝:连接:本地主机”[90067-193]

Posted

技术标签:

【中文标题】org.h2.jdbc.JdbcSQLException:连接断开:“java.net.ConnectException:连接被拒绝:连接:本地主机”[90067-193]【英文标题】:org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-193] 【发布时间】:2018-04-12 06:19:31 【问题描述】:

谁能告诉我我的代码有什么问题

休眠配置

package com.app.EcommerceBackend.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@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;
    



CategoryTestCase

package com.app.EcommerceBackend.test;

import static org.junit.Assert.assertEquals;

import java.sql.SQLException;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.app.EcommerceBackend.dao.CategoryDAO;
import com.app.EcommerceBackend.dto.Category;

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 testCRUDcategory()
    
        //Adding operation
        category = new Category();

        category.setName("Mobile");
        category.setDescription("This is some description for Mobile!");
        category.setImageURL("MOB01.png");

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

        category = new Category();

        category.setName("Television");
        category.setDescription("This is some description for Television!");
        category.setImageURL("TEL02.png");

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

        //Fetching and Updating  Category
        category=categoryDAO.get(2);
        category.setName("TV");
        assertEquals("Successfully updated a single category in the table!", true, categoryDAO.update(category));

        //Deleting A category
        category=categoryDAO.get(1);
        assertEquals("Successfully deleted a single category in the table!", true, categoryDAO.delete(category));

        //Fetching the List
        /*assertEquals("Successfully fetched the list of category from the table!", 1, categoryDAO.list().size());*/
    


出错

  HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException:
    Could not open Hibernate Session for transaction; nested exception is
     org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection

java.sql.SQLException: 无法创建 PoolableConnectionFactory (连接断开:“java.net.ConnectException:连接被拒绝: 连接:本地主机" [90067-193]) org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2294) org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2039) org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533) org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)

org.h2.jdbc.JdbcSQLException:连接断开: “java.net.ConnectException:连接被拒绝:连接:本地主机” [90067-193] org.h2.message.DbException.getJdbcSQLException(DbException.java:345) org.h2.message.DbException.get(DbException.java:168) org.h2.engine.SessionRemote.connectServer(SessionRemote.java:452) org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:329) org.h2.jdbc.JdbcConnection.(JdbcConnection.java:115) org.h2.jdbc.JdbcConnection.(JdbcConnection.java:99) org.h2.Driver.connect(Driver.java:69)

你也可以查看我的gitHub代码https://github.com/sunilgit1/ECommerce

【问题讨论】:

【参考方案1】:

检查您正在运行的 h2 数据库引擎的版本。 并确保您的 pom.xml 文件中的 h2 版本相同。如果不改成同一个版本。

如果 h2 数据库引擎是 1.4.196,那么您通过 pom.xml 为 h2 数据库驱动程序添加的依赖项也应该是 1.4.196。

【讨论】:

【参考方案2】:

我发现,要让 H2 与 tcp 一起工作,您需要在服务器模式下启动 H2

要以服务器模式启动服务器,您需要创建一个 TCP 服务器,所以下面的配置将为您提供 1 个应用程序的连接。

import org.h2.tools.Server;

     @Bean(initMethod = "start", destroyMethod = "stop")
        public Server h2Server1() throws SQLException 
            return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9080");
        

如果您希望更多应用程序使用 TCP 连接到同一个 H2 服务器,您需要再添加一个实例 - 使用不同的端口

 // Second App
    @Bean(initMethod = "start", destroyMethod = "stop")
    public Server h2Server2() throws SQLException 
        return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9081");
    

【讨论】:

以上是关于org.h2.jdbc.JdbcSQLException:连接断开:“java.net.ConnectException:连接被拒绝:连接:本地主机”[90067-193]的主要内容,如果未能解决你的问题,请参考以下文章