分享

Enum字段hibernate持久化时,使用Enum的自定义字段

 roydocs 2014-02-28
           
01import java.util.Map;
02 
03/**
04 * 需要持久化的enum类,都需要实现的接口
05 *
06 * @author weichao
07 *
08 */
09public interface PersistEnum<E extends Enum<?>> {
10 
11    /**
12     * 获取被持久化字段的值
13     *
14     * @return 被持久化字段的值
15     */
16    String getPersistedValue();
17     
18    /**
19     * 由被持久化的字段的值获取枚举类型
20     *
21     * @param persistedValue
22     * @return
23     */
24    E returnEnum(String persistedValue);
25     
26    /**
27     * 获取枚举的所有枚举项
28     *
29     * @return map
30     */
31    Map<String, E> getAllValueMap();
32}

                   

                       

                       

2. [代码]自定义hibernate映射类型    


跳至
                    [1]
                        [2]
                        [3]
                        [4]
   

[全屏预览]


           
001import java.io.Serializable;
002import java.lang.reflect.InvocationTargetException;
003import java.lang.reflect.Method;
004import java.sql.PreparedStatement;
005import java.sql.ResultSet;
006import java.sql.SQLException;
007import java.sql.Types;
008import java.util.Properties;
009 
010import org.hibernate.HibernateException;
011import org.hibernate.usertype.ParameterizedType;
012import org.hibernate.usertype.UserType;
013import org.springframework.util.ObjectUtils;
014 
015/**
016 * 用户持久化枚举类型的用户自定义hibernate映射类型
017 *
018 * <p>
019 * 使用此类型来进行映射的枚举类,必须实现{@link com.lwei.common.PersistEnum} 接口
020 * @author weichao
021 *
022 */
023public class TopEnumType implements UserType,
024        ParameterizedType {
025 
026    private Method returnEnum;
027 
028    private Method getPersistedValue;
029 
030    private Class<Enum<?>> enumClass;
031     
032    private Object enumObject;
033 
034    /**
035     * This method uses the parameter values passed during enum mapping
036     * definition and sets corresponding properties defined
037     */
038    @SuppressWarnings("unchecked")
039    public void setParameterValues(Properties parameters) {
040        if (parameters != null) {
041            try {
042                enumClass = (Class<Enum<?>>) Class.forName(parameters.get("enumClass").toString());
043                enumObject = enumClass.getEnumConstants()[0];
044                getPersistedValue = enumClass.getMethod("getPersistedValue");
045                returnEnum = enumClass.getMethod("returnEnum",
046                        new Class[] { String.class });
047            } catch (SecurityException e) {
048                e.printStackTrace();
049            } catch (NoSuchMethodException e) {
050                e.printStackTrace();
051            } catch (ClassNotFoundException e) {
052                e.printStackTrace();
053            }
054        }
055    }
056 
057    /**
058     * This method maps the database mapping
059     */
060    public int[] sqlTypes() {
061        return new int[] { Types.VARCHAR };
062    }
063 
064    /**
065     * This method maps the class for which user type is created
066     */
067    public Class<?> returnedClass() {
068        return enumClass;
069    }
070 
071    public boolean equals(Object x, Object y) throws HibernateException {
072        return ObjectUtils.nullSafeEquals(x, y);
073    }
074 
075    /**
076     * Fetch the hash code
077     */
078    public int hashCode(Object x) throws HibernateException {
079        return x.hashCode();
080    }
081 
082    /**
083     * Recreate the enum from the resultset
084     */
085    public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
086            throws HibernateException, SQLException {
087 
088        String value = rs.getString(names[0]);
089        Object returnVal = null;
090 
091        if (value == null)
092            return null;
093        else {
094            try {
095                returnVal = returnEnum
096                        .invoke(enumObject, new Object[] { value });
097            } catch (IllegalArgumentException e) {
098                e.printStackTrace();
099            } catch (IllegalAccessException e) {
100                e.printStackTrace();
101            } catch (InvocationTargetException e) {
102                e.printStackTrace();
103            }
104        }
105        return returnVal;
106    }
107 
108    /**
109     * Fetch the data from enum and set it in prepared statement
110     */
111    public void nullSafeSet(PreparedStatement st, Object value, int index)
112            throws HibernateException, SQLException {
113        String prepStmtVal = null;
114 
115        if (value == null) {
116            st.setObject(index, null);
117        } else {
118            try {
119                prepStmtVal = getPersistedValue.invoke(value).toString();
120                st.setString(index, prepStmtVal);
121            } catch (IllegalArgumentException e) {
122                e.printStackTrace();
123            } catch (IllegalAccessException e) {
124                e.printStackTrace();
125            } catch (InvocationTargetException e) {
126                e.printStackTrace();
127            }
128        }
129    }
130 
131    /**
132     * Deep copy method
133     */
134    public Object deepCopy(Object value) throws HibernateException {
135        return value;
136    }
137 
138    public boolean isMutable() {
139        return false;
140    }
141 
142    public Serializable disassemble(Object value) throws HibernateException {
143        Object deepCopy = deepCopy(value);
144 
145        if (!(deepCopy instanceof Serializable))
146            return (Serializable) deepCopy;
147 
148        return null;
149    }
150 
151    public Object assemble(Serializable cached, Object owner)
152            throws HibernateException {
153        return deepCopy(cached);
154    }
155 
156    public Object replace(Object original, Object target, Object owner)
157            throws HibernateException {
158        return deepCopy(original);
159    }
160 
161}

                   

                       

                       

3. [代码]一个实现了持久化枚举接口的枚举类    


跳至
                    [1]
                        [2]
                        [3]
                        [4]
   

[全屏预览]


           
01import java.util.Map;
02import java.util.TreeMap;
03 
04import com.lwei.common.TopEnum;
05 
06public enum OrganType implements PersistEnum<OrganType>{
07    // 利用构造函数传参
08    ORGANTYPE_DEPARTMENT("D"), // 部门
09    ORGANTYPE_ORGANMANAGER("M"), // 管理机构
10    ORGANTYPE_NONE("N");   //普通机构 无特殊含意的机构,类似企业中的总公司和分支机构,只有上下级关系。
11 
12    private static final Map<String, OrganType> map = new TreeMap<String, OrganType>();
13     
14    static {
15        map.put(ORGANTYPE_DEPARTMENT.getOrgType(), ORGANTYPE_DEPARTMENT);
16        map.put(ORGANTYPE_ORGANMANAGER.getOrgType(), ORGANTYPE_ORGANMANAGER);
17        map.put(ORGANTYPE_NONE.getOrgType(), ORGANTYPE_NONE);
18    }
19     
20    // 定义私有变量
21    private String orgType ;
22 
23    // 构造函数,枚举类型只能为私有
24     private OrganType(String _orgType) {
25         this . orgType = _orgType;
26     }
27 
28    public String getOrgType() {
29        return orgType;
30    }
31 
32    @Override
33    public String getPersistedValue() {
34        return getOrgType();
35    }
36 
37    @Override
38    public OrganType returnEnum(String persistedValue) {
39        return map.get(persistedValue);
40    }
41 
42    @Override
43    public Map<String, OrganType> getAllValueMap() {
44        return map;
45    }        
46}

                   

                       

                       

4. [代码]在持久化对象中定义枚举字段映射    


跳至
                    [1]
                        [2]
                        [3]
                        [4]
   

[全屏预览]


           
1@Column(name = "organType", nullable = false, length = 1)
2@Type(type="com.lwei.persistence.TopEnumType",
3    parameters={@Parameter(name="enumClass",value="com.lwei.org.domain.entities.OrganType")})
4private OrganType organType;

                   

                   

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多