JSP 中Hibernate实现映射枚举类型
JSP中Hibernate实现映射枚举类型
问题:
JavaBO类Gender是枚举类型,想在数据库中存成字符串格式,如何编写hbm.xml?
publicenumGender{
UNKNOWN("Unknown"),
MALE("Male"),
FEMALE("Female");
privateStringkey;
privateGender(finalStringkey){
this.key=key;
}
publicgetGender(Stringkey){
for(Gendergender:Gender.values()){
if(key.euqals(gender.getKey()))
returngender;
}
thrownewNoSuchElementException(key);
}
}
使用UserType:
publicclassGenderUserTypeimplementsUserType{
privatestaticint[]typeList={Types.VARCHAR};
/*
*ReturntheSQLtypecodesforthecolumnsmappedbythistype.
*Thecodesaredefinedonjava.sql.Types.*/
/**设置和Gender类的sex属性对应的字段的SQL类型*/
publicint[]sqlTypes(){
returntypeList;
}
/*TheclassreturnedbynullSafeGet().*/
/**设置GenderUserType所映射的Java类:Gender类*/
publicClassreturnedClass(){
returnGender.class;
}
/**指明Gender类是不可变类*/
publicbooleanisMutable(){
returnfalse;
}
/*
*Returnadeepcopyofthepersistentstate,stoppingatentitiesandat
*collections.Itisnotnecessarytocopyimmutableobjects,ornull
*values,inwhichcaseitissafetosimplyreturntheargument.
*/
/**返回Gender对象的快照,由于Gender类是不可变类,因此直接将参数代表的Gender对象返回*/
publicObjectdeepCopy(Objectvalue){
return(Gender)value;
}
/**比较一个Gender对象是否和它的快照相同*/
publicbooleanequals(Objectx,Objecty){
//由于内存中只可能有两个静态常量Gender实例,
//因此可以直接按内存地址比较
return(x==y);
}
publicinthashCode(Objectx){
returnx.hashCode();
}
/*
*RetrieveaninstanceofthemappedclassfromaJDBCresultset.Implementors
*shouldhandlepossibilityofnullvalues.
*/
/**从JDBCResultSet中读取key,然后返回相应的Gender实例*/
publicObjectnullSafeGet(ResultSetrs,String[]names,Objectowner)
throwsHibernateException,SQLException{
//从ResultSet中读取key
Stringsex=(String)Hibernate.STRING.nullSafeGet(rs,names[0]);
if(sex==null){returnnull;}
//按照性别查找匹配的Gender实例
try{
returnGender.getGender(sex);
}catch(java.util.NoSuchElementExceptione){
thrownewHibernateException("BadGendervalue:"+sex,e);
}
}
/*
*Writeaninstanceofthemappedclasstoapreparedstatement.Implementors
*shouldhandlepossibilityofnullvalues.
*Amulti-columntypeshouldbewrittentoparametersstartingfromindex.
*/
/**把Gender对象的key属性添加到JDBCPreparedStatement中*/
publicvoidnullSafeSet(PreparedStatementst,Objectvalue,intindex)
throwsHibernateException,SQLException{
Stringsex=null;
if(value!=null)
sex=((Gender)value).getKey();
Hibernate.String.nullSafeSet(st,sex,index);
}
/*
*Reconstructanobjectfromthecacheablerepresentation.Attheveryleastthis
*methodshouldperformadeepcopyifthetypeismutable.(optionaloperation)
*/
publicObjectassemble(Serializablecached,Objectowner){
returncached;
}
/*
*Transformtheobjectintoitscacheablerepresentation.Attheveryleastthis
*methodshouldperformadeepcopyifthetypeismutable.Thatmaynotbeenough
*forsomeimplementations,however;forexample,associationsmustbecachedas
*identifiervalues.(optionaloperation)
*/
publicSerializabledisassemble(Objectvalue){
return(Serializable)value;
}
/*
*Duringmerge,replacetheexisting(target)valueintheentitywearemergingto
*withanew(original)valuefromthedetachedentitywearemerging.Forimmutable
*objects,ornullvalues,itissafetosimplyreturnthefirstparameter.For
*mutableobjects,itissafetoreturnacopyofthefirstparameter.Forobjects
*withcomponentvalues,itmightmakesensetorecursivelyreplacecomponentvalues.
*/
publicObjectreplace(Objectoriginal,Objecttarget,Objectowner){
returnoriginal;
}
}
然后再hbm.xml中定义映射关系:
延伸:
为每个枚举类型定义一个UserType是比较麻烦的,可以定义一个抽象类。
例如扩展下例即可适用于所有保存为index的枚举类型
publicabstractclassOrdinalEnumUserType>implementsUserType{ protectedClass clazz; protectedOrdinalEnumUserType(Class clazz){ this.clazz=clazz; } privatestaticfinalint[]SQL_TYPES={Types.NUMERIC}; publicint[]sqlTypes(){ returnSQL_TYPES; } publicClass>returnedClass(){ returnclazz; } publicEnullSafeGet(ResultSetresultSet,String[]names,Objectowner) throwsHibernateException,SQLException{ //Hibernate.STRING.nullSafeGet(rs,names[0]) intindex=resultSet.getInt(names[0]); Eresult=null; if(!resultSet.wasNull()){ result=clazz.getEnumConstants()[index]; } returnresult; } publicvoidnullSafeSet(PreparedStatementpreparedStatement, Objectvalue,intindex)throwsHibernateException,SQLException{ if(null==value){ preparedStatement.setNull(index,Types.NUMERIC); }else{ //Hibernate.String.nullSafeSet(st,sex,index); preparedStatement.setInt(index,((E)value).ordinal()); } } publicObjectdeepCopy(Objectvalue)throwsHibernateException{ returnvalue; } publicbooleanisMutable(){ returnfalse; } publicObjectassemble(Serializablecached,Objectowner) throwsHibernateException{ returncached; } publicSerializabledisassemble(Objectvalue)throwsHibernateException{ return(Serializable)value; } publicObjectreplace(Objectoriginal,Objecttarget,Objectowner) throwsHibernateException{ returnoriginal; } publicinthashCode(Objectx)throwsHibernateException{ returnx.hashCode(); } publicbooleanequals(Objectx,Objecty)throwsHibernateException{ if(x==y) returntrue; if(null==x||null==y) returnfalse; returnx.equals(y); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!