I'm new to mybatis. I am trying to map a JDBC integer to a custom class. All the examples that I have seen on this have used annotations, is it possible to not use annotations and do this? Any example would be greatly appreciated.
Sreekanth
I'm new to mybatis. I am trying to map a JDBC integer to a custom class. All the examples that I have seen on this have used annotations, is it possible to not use annotations and do this? Any example would be greatly appreciated.
Sreekanth
It is definitely possible and is described in general in Configuration and in Mapper sections of the documentation.
Define the handler first:
@MappedJdbcTypes(JdbcType.INTEGER)
public class MyClassHandler extends BaseTypeHandler<MyClass> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
MyClass parameter, JdbcType jdbcType) throws SQLException {
ps.setInt(i, parameter.asInt());
}
@Override
public MyClass getNullableResult(ResultSet rs, String columnName)
throws SQLException {
int val = rs.getInt(columnName);
if (rs.wasNull())
return null;
else
return MyClass.valueOf(val);
}
@Override
public MyClass getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
int val = rs.getInt(columnIndex);
if (rs.wasNull())
return null;
else
return MyClass.valueOf(val);
}
@Override
public MyClass getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
int val = cs.getInt(columnIndex);
if (cs.wasNull())
return null;
else
return MyClass.valueOf(val);
}
}
Then configure it in mybatis-config.xml
:
<typeHandlers>
<typeHandler handler="my.company.app.MyClassHandler"/>
</typeHandlers>
Now you can use it in xml mappers. If you have a class
class SomeTypeEntity {
private MyClass myClassField;
};
For querying the field configure handler in the resultMap
like this:
<resultMap id="someMap" type="SomeTypeEntity">
<result property="myClassField" column="my_class_column" typeHandler="my.company.app.MyClassHandler"/>
</resultMap>
For insert
/update
use it like this:
<update id="updateSomeTypeWithMyClassField">
update some_type
set
my_class_column = @{someTypeEntity.myClassField, typeHandler=my.company.app.MyClassHandler},
</update>
for mapper method:
void updateSomeTypeWithMyClassField(@Param("someTypeEntity") SomeTypeEntity entity);