java - Mybatis enum select by id -
my mybatis code doesn't load enum type (version: 3.4.4).
at mysql database have table cartype field int(11) type. in java created enum handling car types:
public enum cartype { sedan(1), limusin(2), wagon(3); private int id; cartype(int id) { this.id = id; } public int getid() { return this.id; }
car mapper xml looks (contains no data):
<select id="selectcar" parametertype="car" resultmap="carresultmap"> select * cars car_name="#{carname}"; </select> <resultmap id="carresultmap" type="car"> <id property="id" column="car_name"/> <result property="cartype" column="cartype"/> </resultmap>
finally bean followings:
public class car { private integer id; private cartype cartype; }
the bean contains getters , setters too.
when try car in java thorws following exception: caused by: java.lang.illegalargumentexception: no enum constant org.data.bean.cartype.1 @ java.lang.enum.valueof(enum.java:238) @ org.apache.ibatis.type.enumtypehandler.getnullableresult(enumtypehandler.java:49) @ org.apache.ibatis.type.enumtypehandler.getnullableresult(enumtypehandler.java:26) @ org.apache.ibatis.type.basetypehandler.getresult(basetypehandler.java:66)
it's enum name needs stored in database, not id.
take here . default enumtypehandler expects varchar:
varchar string compatible type, code stored (not index).
if want or have store id need custom typehandler. this:
public class cartypetypehandler implements typehandler<cartype> { public void setparameter(preparedstatement ps, int paramint, cartype paramtype, jdbctype jdbctype) throws sqlexception { ps.setint(paramint, paramtype.getid()); } @override public cartype getresult(resultset rs, string param) throws sqlexception { return cartype.get(rs.getint(param)); } @override public cartype getresult(callablestatement cs, int col) throws sqlexception { return cartype.get(cs.getint(col)); } }
it convenient have lookup method in enum too:
public static cartype get(int code) { for(cartype s : values()) { if(s.id == code) return s; } return null; }
you may need indicate enum type explicitly in mapper. add javatype parameter (i'm including sample type handler definition):
<result property="cartype" column="cartype" javatype="path.to.package.cartype" typehandler="path.to.package.cartypetypehandler"/>
Comments
Post a Comment