在旧数据库中映射 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/