---
title: "自定义hibernate type"
author: "dragon0929"
date: "2010-06-21T17:56:40Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-type"
draft: false
lastmod: "2010-06-21T17:58:13Z"
id: 695877
url: "https://dragon0929.iteye.com/blog/695877"
---

因为CountryCode是从其它系统导过来的，有时出现了空格，所以自定义了一个TrimmedString

 

&lt;hibernate-mapping&gt;  
    &lt;class name="au.com.at2.dictionaries.country.Country" table="COUNTRY" lazy="false"&gt;  
        &lt;id name="countryCode" column="CountryCode" type="au.com.at2.hibernate.TrimmedString " /&gt;

        &lt;property name="countryName" column="CountryName"/&gt;  
        &lt;property name="internationalPrefixCode" column="InternationalPrefixCode"/&gt;  
    &lt;/class&gt;

    &lt;query name="Country.findAll" cacheable="true"  
           cache-region="/au/com/at2/dictionaries/AllCountries"&gt;  
        from Country c order by c.countryName  
   &lt;/query&gt;  
&lt;/hibernate-mapping&gt;

 

public class TrimmedString implements UserType {  
    public TrimmedString() {  
        super();  
    }

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

    public Class returnedClass() {  
        return String.class;  
    }

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

    public Object nullSafeGet(ResultSet rs, String\[] names, Object owner)  
            throws HibernateException, SQLException {  
        String val = rs.getString(names\[0]);  
        return val != null ? val.trim() : null;  
    }

    public void nullSafeSet(PreparedStatement st, Object value, int index)  
            throws HibernateException, SQLException {  
        String val = (String) value;  
        st.setString(index, val != null ? val.trim() : null);  
    }

    public Object deepCopy(Object value) throws HibernateException {  
        if (value == null)  
            return null;  
        return new String((String) value);  
    }

    public boolean isMutable() {  
        return false;  
    }

    public Object assemble(Serializable serializable, Object object)  
            throws HibernateException {  
        return serializable;  
    }

    public Serializable disassemble(Object object) throws HibernateException {  
        return (Serializable) object;  
    }

    public int hashCode(Object object) throws HibernateException {  
        return object.hashCode();  
    }

    public Object replace(Object object, Object object1, Object object2)  
            throws HibernateException {  
        return object;  
    }