问题描述
我有一个 Grails 应用程序,可以在 SQL Server 或 Oracle 后端运行.我使用 GORM 作为 ORM.
I have a Grails application that will run against either a SQL Server or Oracle backend. I am using GORM as an ORM.
我想以支持两种数据库类型的方式映射一个大文本字段.在我的 Grails 域类中,我有类似的东西:
I want to map a large text field in a way that supports both database types. In my Grails domain class I have something like:
class Note {
String content
static constraints = {
content nullable: false, blank: false
}
}
然后我声明如下所示的数据库表:
I then declare database tables that look like this:
-- oracle
CREATE TABLE NOTE
(
id NUMBER(19, 0) NOT NULL,
version NUMBER(19, 0) NOT NULL,
content CLOB NOT NULL
);
-- SQL Server
CREATE TABLE NOTE
(
id NUMERIC(19, 0) NOT NULL,
version NUMERIC(19, 0) NOT NULL,
content NVARCHAR(MAX) NOT NULL
);
GORM 在启动时以 validate
模式运行,我找不到 Oracle 和 SQL Server 数据类型以及允许存储或大文本字段的 GORM 映射的组合,而 GORM 无法启动正确.
GORM is running in validate
mode on startup, and I can't find a combination of Oracle and SQL Server data types and GORM mappings that allow the storage or large text fields without GORM failing to start correctly.
我试过了:
在
mappings
中将类型设置为text
,但这似乎不起作用.Oracle 抱怨希望content
字段的类型为long
,而 SQL Server 在这些情况下需要一种text
类型.
setting the type to
text
inmappings
, but this doesn't seem to work. Oracle complains about expecting thecontent
field to be of typelong
, and SQL Server wants a type oftext
in these circumstances.
将 type
设置为 clob
,它通过了模式验证,但不允许我将该字段设置为字符串值 - GORM 期望数据为输入 CLOB
.
setting the type
to clob
, which passes schema validation but then doesn't allow me to set the field as a string value - GORM expects data of type CLOB
.
我应该如何配置我的数据库定义和 GORM 以使其工作?
How should I configure my database definitions and GORM to make this work?
推荐答案
尽管很黑,但最终出现了一个解决方案:通过在启动时查询 Grails 配置,您可以选择合适的数据类型.
As hackish as it is, a solution eventually emerged: by querying the Grails configuration at startup time, you can select an appropriate data type.
class Note {
String content
static constraints = {
content nullable: false, blank: false
}
static mappings = {
content sqlType: DbSupport.bigStringType
}
}
class DbSupport {
static def getBigStringType() {
// examine which hibernate dialect is selected, and pick
// an appropriate type mapping for that database type:
def dialect = ApplicationHolder.application.config.dataSource.dialect
switch (dialect) {
case "org.hibernate.dialect.SQLServerDialect":
return "nvarchar"
break
case "org.hibernate.dialect.Oracle10gDialect":
return "clob"
break
}
}
}
这篇关于GORM:不可知地映射大文本字段数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!