hibernate 自定义枚举类型映射

自定义类型MyEnumType 
package com.binarysource.hinernate;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

public class MyEnumType implements UserType, ParameterizedType{
    private Field typeField;
    private Class> enumClass;
    private Method method;

	
	@SuppressWarnings("unchecked")
	@Override
	public void setParameterValues(Properties parameters) {
		if (parameters != null) {
            try {
                enumClass = (Class>) Class.forName(parameters.get("enumClass").toString());
                typeField=enumClass.getDeclaredField("type");
                typeField.setAccessible(true);
                try {
			method=enumClass.getDeclaredMethod("getByType", String.class);
		} catch (NoSuchMethodException e) {
		}
                
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
		e.printStackTrace();
	    }
        }
		
	}

	@Override
	public int[] sqlTypes() {
		return new int[] { Types.VARCHAR };
	}

	@Override
	public Class returnedClass() {
		return enumClass;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		 return (x!=null && y!=null) ? x.equals(y) : false;
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		
		return x.hashCode();
	}

 
	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
			throws HibernateException, SQLException {

        String value = rs.getString(names[0]);
        Object returnVal = null;
 
        if (value == null)
            return null;
        else {
            try {
            	if(method!=null){
            		return method.invoke(null, value);
            	}
            	Enum[] consts=enumClass.getEnumConstants();
            	for (Enum enum1 : consts) {
            		String type=(String)typeField.get(enum1);
            		if(value.equals(type)){
            			return enum1;
            		}
    			}
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return returnVal;
	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
			throws HibernateException, SQLException {
		  String prepStmtVal = null;
		  
	        if (value == null) {
	            st.setObject(index, null);
	        } else {
	            try {
	                prepStmtVal = typeField.get(value).toString();
	                st.setString(index, prepStmtVal);
	            } catch (IllegalArgumentException e) {
	                e.printStackTrace();
	            } catch (IllegalAccessException e) {
	                e.printStackTrace();
	            }
	        }
		
	}
    
  

	/**
     * Deep copy method
     */
    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }
 
    public boolean isMutable() {
        return false;
    }
 
    public Serializable disassemble(Object value) throws HibernateException {
        Object deepCopy = deepCopy(value);
 
        if (!(deepCopy instanceof Serializable))
            return (Serializable) deepCopy;
 
        return null;
    }
 
    public Object assemble(Serializable cached, Object owner)
            throws HibernateException {
        return deepCopy(cached);
    }
 
    public Object replace(Object original, Object target, Object owner)
            throws HibernateException {
        return deepCopy(original);
    }

}


定义枚举类型

package com.binarysource.hibernate.enumeration;

public enum SexType {


	
	Male("0","男"),
	Female("1","女");
	
	private String type;
	private String name;
	
	public static String getNameByType(String type){
		SexType[] modes = SexType.values();
		for (SexType mode : modes) {
			if(mode.type.equals(type)){
				return mode.name;
				
			}
		}
		return null;
	}
	
	public static SexType getSexTypeByName(String name){
		SexType[] modes = SexType.values();
		for (SexType mode : modes) {
			if(mode.name.equals(name)){
				return mode;
				
			}
		}
		return null;
	}
	
	private SexType(String type,String name){
		this.type = type;
		this.name = name;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}
	
}

entity中使用枚举


	   private SexType sexType;
	    @Type(type="com.binarysource.hibernate.MyEnumType",parameters={@Parameter(name="enumClass",value="com.binarysource.hibernate.SexType")})
	    public SexType getSexType() {
	        return sexType;
	    }

	    public void setSexType(SexType sexType) {
	        this.sexType = sexType;
	    }


你可能感兴趣的:(hibernate 自定义枚举类型映射)