我在我提到的 hibernate 配置文件中使用 Mysql 和早期版本
<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
作为连接 url,其中 TestDB
是我要连接的架构。
我想在配置文件中指定默认模式
<property name="hibernate.connection.url">jdbc:mysql://localhost</property>
<property name="hibernate.default_schema">TestDB</property>
但它不能以这种方式工作,它给了我一个错误,说
java.sql.SQLException: No database selected
任何人都可以帮我举一个如何在 hibernate 配置文件中使用 hibernate.default_schema
、 hibernate.default_catalog
的示例吗?
最佳答案
您应该使用 hibernate.default_catalog
而不是 hibernate.default_schema
。
根据MySql documentation连接 URL 应采用以下格式:
protocol//[hosts][/database][?properties]
哪里
database
The default database or catalog to open. If the database is not specified, the connection is made with no default database. In this case, either call the
setCatalog()
method on theConnection
instance, or specify table names using the database name (that is,SELECT dbname.tablename.colname FROM dbname.tablename
...) in your SQL statements. Opening a connection without specifying the database to use is, in general, only useful when building tools that work with multiple databases, such as GUI database managers.
假设我们有以下 MySql 数据库:
create database DB_A;
create database DB_B;
create table DB_A.TST_EMPLOYEE(
emp_id int primary key,
emp_name varchar(100)
);
create table DB_B.TST_EMPLOYEE(
emp_id int primary key,
emp_name varchar(100)
);
然后我们可以通过以下方式在hibernate.cfg.xml
中指定数据库连接:
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
<property name="hibernate.default_catalog">DB_A</property>
<property name="hibernate.connection.username">your_user</property>
<property name="hibernate.connection.password">your_pass</property>
按以下方式声明 DB_A.TST_EMPLOYEE
和 DB_B.TST_EMPLOYEE
表的实体:
@Entity
@Table(name = "TST_EMPLOYEE")
public class EmployeeA
{
// ...
}
@Entity
@Table(name = "TST_EMPLOYEE", catalog = "DB_B")
public class EmployeeB
{
// ...
}
然后以通常的方式使用它们。还为native queries您可以使用 {h-catalog}
占位符作为 hibernate.default_catalog
属性中指定的默认目录。
附注我不得不说,目录 和模式 概念在不同的数据库中可能具有完全不同的含义。请参阅this供引用。
关于mysql - 如何使用 hibernate.default_schema 和 hibernate.default_catalog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60447970/