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<Enum<?>> enumClass;
    private Method method;

	
	@SuppressWarnings("unchecked")
	@Override
	public void setParameterValues(Properties parameters) {
		if (parameters != null) {
            try {
                enumClass = (Class<Enum<?>>) 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;
	    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值