hibernate - 使用 Grails GORM 从旧数据库中的 char 字段中去除尾随空格

标签 hibernate grails grails-orm hibernate-mapping

在旧数据库中映射 char 字段时,有哪些可能的解决方案可以去除尾随空格?

我看到以下选项:

  • 在使用时( Controller 、 View 等)调用 .trim()
  • 重写属性访问器以返回 .trim()
  • 使用 Hibernate UserType 修剪空格

我倾向于重写属性访问器,以便域属性在整个应用程序中保持一致。

最佳答案

我使用全局映射的 Hibernate UserType 并且效果很好(基于 http://www.hibernate.org/388.html 的实现,但针对 UserType 接口(interface)的重大更改进行了更新):

package company

import org.hibernate.Hibernate
import org.hibernate.usertype.UserType

import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Types

/**
 * Map CHAR(x) types to String: trim when getting and setting the CHAR(x)
 * based on www.hibernate.org/388.html
 */
public class TrimmedString implements UserType {
    public TrimmedString() {
    }

    public int[] sqlTypes() {
        return [Types.CHAR] as int[];
    }

    @SuppressWarnings("unchecked")
    public Class returnedClass() {
        return String.class;
    }

    public boolean equals(Object x, Object y) {
        return (x == y) || (x != null && y != null && (x.equals(y)));
    }

    public Object nullSafeGet(ResultSet inResultSet, String[] names, Object o) throws SQLException {
        String val = (String) Hibernate.STRING.nullSafeGet(inResultSet, names[0]);
        return val == null ? null : val.trim();
    }

    public void nullSafeSet(PreparedStatement inPreparedStatement, Object o, int i) throws SQLException {
        String val = (String) o;
        inPreparedStatement.setString(i, val);
    }

    public Object deepCopy(Object o) {
        if (o == null) {
            return null;
        }
        return new String(((String) o));
    }

    public boolean isMutable() {
        return false;
    }

    public Object assemble(Serializable cached, Object owner) {
        return cached;
    }

    public Serializable disassemble(Object value) {
        return (Serializable) value;
    }

    public Object replace(Object original, Object target, Object owner) {
        return original;
    }

    public int hashCode(Object x) {
        return x.hashCode();
    }
}

Groovy.config 中的全局映射:

grails.gorm.default.mapping = {
    'user-type'(type: company.TrimmedString, class: String) //map Char(x) columns mapped to string fields as trimmed string
}

关于hibernate - 使用 Grails GORM 从旧数据库中的 char 字段中去除尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668315/

相关文章:

java - hibernate 注释

java - 重构闭包标准以修复列表中表达式的最大数量为 1000

hibernate - 延迟加载在带有 Hibernate 的 JPA 中不起作用

java - 使用 Hibernate 分区

java - 如何在多线程环境下mysql hibernate使用一张表的自增值插入多张表

eclipse - 有没有一种方法可以在Eclipse GGTS中对项目进行排序?

Grails:.save(flush:flush, insert:true) 与 .save(flush:true) 有何不同

hibernate - Grails 2.4.4 完全忽略提取 :'join' *使用 PostgreSQL 时*

java - 在 Grails + Oracle + CLOB 中使用 PropertyNotInList 时出错

grails - 如何检测 afterUpdate|beforeUpdate GORM 方法中哪个字段已更新