这两天有点时间,看了一下mybatis,尝试把一个ibatis的项目用mybatis替换。在使用过程中,基本的配置等这里就不累述了,网上一搜一堆。这里主要讲我在使用过程中遇到的两个花了我比较长时间解决的问题,一个是结果集的枚举映射;另一个就是物理分页。
首先结果集枚举映射:
假设我们有这么一个对象
- public enum Status {
- // 默认0, 可用1, 不可用-1
- DEFAULT(0), AVAILABLE(1), UNAVAILABLE(-1);
- private int value = 0;
- Status(int value){
- this.value = value;
- }
- public long getValue() {
return this.value;
}
- public static Status getStatus(int value){
- Status status = null;
- for(Status s : Status.values()){
- if(s.getValue() == value){
- status = s;
- break;
- }
- }
- return status;
- }
- }
- public class StatusTypeHandler extends BaseTypeHandler implements TypeHandler {
- @Override
- public void setNonNullParameter(PreparedStatement ps, int i,
- Object parameter, JdbcType jdbcType) throws SQLException {
- ps.setInt(i, ((Status)parameter).ordinal());
-
- @Override
public Object getNullableResult(ResultSet rs, String columnName)
throws SQLException {
Integer value = rs.getInt(columnName);
return null == value ? null : Status.getStatus(value);
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
Integer value = cs.getInt(columnIndex);
return null == value ? null : Status.getStatus(value);
} - }