mysql - 如何使用 hibernate.default_schema 和 hibernate.default_catalog

标签 mysql hibernate

我在我提到的 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_schemahibernate.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 the Connection 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_EMPLOYEEDB_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/

相关文章:

C# Mysql - 在异步等待服务器的数据库查询上使用锁

java - 使用java jdbc在vista上连接mysql,通讯异常,尝试了常见的答案

php - Yii 1 : CActiveDataProvider does not return all records

java - 截断所有表,清除一级和二级 hibernate 缓存的简单方法?

java - 非法参数异常 : argument type mismatch in Hibernate

java - JPA 静态元模型生成器的正确 gradle 设置是什么?

java - hibernate createAlias with 子句生成错误的查询

java - 如何处理 JPA 中的分页(标准和谓词)

php - 修复损坏的 UTF-8 编码

mysql - 如何显示多个表中包含特定值的行