Hibernate配置报错:连接被拒绝,请求排查代码问题
Hey there, let's break down this H2 connection refusal error you're hitting with your Hibernate config. The error clearly says your app can't reach the H2 server running on localhost, so let's walk through the most common fixes tied to your setup.
- If you're using embedded H2 mode (file-based storage), you don't need a separate server. But if your config is set for TCP/server mode, you have to start the H2 server first—either via the H2 console, command line, or your IDE's built-in tools. Forgetting to launch the server is the #1 cause of this "connection refused" error.
Looking at your code, you're using BasicDataSource from Apache DBCP2. Let's make sure your URL matches your intended H2 mode:
- Embedded mode: Should look like
jdbc:h2:file:/path/to/your/local/db/file;DB_CLOSE_ON_EXIT=FALSE(nolocalhostortcp://prefix here) - Server/TCP mode: Must include host, port, and database name, e.g.,
jdbc:h2:tcp://localhost:9092/~/your-db-name(default port is 9092—if you changed the server's port, update this URL to match) - Common mistake: Accidentally mixing modes (using a
tcp://URL without running the server, or vice versa).
- Ensure your
driverClassNameis set toorg.h2.Driver(avoid outdated or incorrect driver names) - Double-check your build file has the correct H2 dependency. For your error code (90067-193), you're using H2 version 1.4.193—make sure it's properly included:
<!-- Maven example --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.193</version> <scope>runtime</scope> </dependency>
If you're configuring both BasicDataSource and Hibernate connection properties, make sure they don't conflict. For BasicDataSource, set all connection details directly on the bean instead of duplicating them in Hibernate properties:
@Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:tcp://localhost:9092/~/your-db"); // Adjust to your mode dataSource.setUsername("sa"); dataSource.setPassword(""); // Default H2 password is empty return dataSource; }
- Rare but possible: Your local firewall might be blocking the default H2 port (9092). Try temporarily disabling it to test, or change the H2 server port and update your URL accordingly.
- Check if another app is using port 9092: Use
netstat -ano | findstr :9092(Windows) orlsof -i :9092(Linux/macOS) to verify.
If you're using the H2 console to debug, make sure its connection settings (URL, port, database name) exactly match what's in your Hibernate config. Mismatches here can lead to confusion about whether the database is actually accessible.
If you can share the full HibernateConfig code (especially the complete dataSource and hibernateProperties beans), I can help narrow things down even further!
内容的提问来源于stack exchange,提问作者sunil

