如何在Hibernate配置中使用hibernate.default_schema与hibernate.default_catalog
Hey there, let's figure out how to fix that No database selected error you're hitting with Hibernate and MySQL!
First, let's break down the issue: When you use the bare JDBC URL jdbc:mysql://localhost without specifying a database, the connection doesn't automatically select any schema. While hibernate.default_schema is meant to set a default, some older MySQL JDBC drivers or Hibernate versions don't translate this setting into an automatic USE TestDB command on connection — hence the error.
Here are working configuration examples for both XML and properties files, plus clarity on default_schema vs default_catalog:
1. XML Configuration Example
<!-- Core database connection settings --> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost?useSSL=false&serverTimezone=UTC</property> <property name="hibernate.connection.username">your_db_username</property> <property name="hibernate.connection.password">your_db_password</property> <!-- Set default schema (works for MySQL) --> <property name="hibernate.default_schema">TestDB</property> <!-- Optional: default_catalog (in MySQL, this behaves the same as default_schema) --> <!-- Use this if you need compatibility with databases that distinguish catalogs/schemas --> <!-- <property name="hibernate.default_catalog">TestDB</property> -->
2. Properties File Example
# Core connection settings hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost?useSSL=false&serverTimezone=UTC hibernate.connection.username=your_db_username hibernate.connection.password=your_db_password # Default schema for MySQL hibernate.default_schema=TestDB # Optional: Default catalog (equivalent to schema in MySQL) # hibernate.default_catalog=TestDB
Key Notes to Avoid the Error
- Use the latest MySQL JDBC Driver: Older versions (like 5.x) have limited support for
hibernate.default_schema. Stick tomysql-connector-java:8.0.xor newer. - Add
currentSchemato the JDBC URL (fallback): If you still get the error, add thecurrentSchemaparameter to your URL to force the driver to select the database on connection:jdbc:mysql://localhost?currentSchema=TestDB&useSSL=false&serverTimezone=UTC - Check Entity Annotations: If your entity classes use
@Table(schema = "OtherDB"), that will override the globalhibernate.default_schemasetting.
What's the Difference Between default_schema and default_catalog?
In MySQL, schema and catalog are essentially synonyms — both refer to a database. However, in other databases (like SQL Server or PostgreSQL), catalogs are higher-level containers for schemas. Use hibernate.default_catalog if you're building cross-database compatible code; for MySQL-specific setups, hibernate.default_schema is sufficient.
内容的提问来源于stack exchange,提问作者RajGopalbh4

