如何使用 GORM 验证字段是否为空字符串?
How to verify if a field is an empty string with GORM?
我有一个 GORM 查询,我需要让它避免一个对于遗留系统问题可能是空字符串的字段。
目前,我的查询是:
def things = Thing.withCriteria{
resultTransformer CriteriaSpecification.ALIAS_TO_ENTITY_MAP
createAlias 'factor', 'f'
eq 'active', true
isNotNull 'title' // this field may be an empty string
isNotNull 'content' // this field also may be an empty string
// <-- and here I'd like to include sth like isEmpty 'title'
not {
inList 'f.id', factors
}
projections{
property 'id' , 'id'
property 'f.name' , 'name'
property 'title' , 'title'
property 'content' , 'content'
property 'f.id' , 'factorId'
}
}
我没有在文档中找到任何解决方案,但我感觉这个解决方案应该是纯 SQL。可能吗?有什么建议吗?
您是否尝试过将此语句添加到条件中?
ne title, ""
Grails 标准依赖于 hibernate Restrictions,因此它支持的所有内容也可以在 grails 标准中使用。
否则你也可以使用sql restrictions (see Using SQL Restrictions section):
sqlRestriction "char_length(title) > 0"
记住这里的title
指的是数据库中真实的列名。如果你想有一个更可靠的代码,你可以在模型中包含字段(列名)的静态映射:
static mapping = {
title column: 'title'
}
通过这种方式,您应该避免因数据库特定命名行为(如果有的话)而产生的错误。
我有一个 GORM 查询,我需要让它避免一个对于遗留系统问题可能是空字符串的字段。
目前,我的查询是:
def things = Thing.withCriteria{
resultTransformer CriteriaSpecification.ALIAS_TO_ENTITY_MAP
createAlias 'factor', 'f'
eq 'active', true
isNotNull 'title' // this field may be an empty string
isNotNull 'content' // this field also may be an empty string
// <-- and here I'd like to include sth like isEmpty 'title'
not {
inList 'f.id', factors
}
projections{
property 'id' , 'id'
property 'f.name' , 'name'
property 'title' , 'title'
property 'content' , 'content'
property 'f.id' , 'factorId'
}
}
我没有在文档中找到任何解决方案,但我感觉这个解决方案应该是纯 SQL。可能吗?有什么建议吗?
您是否尝试过将此语句添加到条件中?
ne title, ""
Grails 标准依赖于 hibernate Restrictions,因此它支持的所有内容也可以在 grails 标准中使用。
否则你也可以使用sql restrictions (see Using SQL Restrictions section):
sqlRestriction "char_length(title) > 0"
记住这里的title
指的是数据库中真实的列名。如果你想有一个更可靠的代码,你可以在模型中包含字段(列名)的静态映射:
static mapping = {
title column: 'title'
}
通过这种方式,您应该避免因数据库特定命名行为(如果有的话)而产生的错误。