Java MyBatis mutate返回了对象/自定义映射器

时间:2017-12-29 19:13:01

标签: java mybatis spring-mybatis

提供以下的SQL架构:

CREATE TABLE Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255)
)

我想要一个像这样的映射器:

interface PersonMapper {
    String getFullName(Object row) {
        return row.FirstName + " " + row.LastName;
    }

    @Results(id = "person", value = {
            @Result(column = "PersonID", javaType = Integer.class, property = "id"),
            @Result(column = "LastName", javaType = String.class, property = "lastName"),
            @Result(column = "FirstName", javaType = String.class, property = "firstName"),
            @Result(PersonMapper::getFullName, javaType = String.class, property = "fullName")
    })
    @Select("SELECT * FROM Persons")
    List<PersonEntity> getPersons();
}

所以我可以这样做:

public void someFunction() {
    List<PersonEntity> persons = personMapper.getPersons();
    log.info(persons.get(0).getFullName())
}

除了在personMapper.getPersons()之后操作结果时,不确定如何做到这一点。

1 个答案:

答案 0 :(得分:0)

我找到了答案,你可以设置结果TypeHandler:

    @Result(column = "DayOfWeek",
            javaType = Integer.class,
            property = "dayOfWeek",
            typeHandler = DayOfWeekTypeHandler.class),

然后定义TypeHandler:

public class DayOfWeekTypeHandler extends BaseTypeHandler<DayOfWeek> {
    @Override
    public void setNonNullParameter(
            PreparedStatement ps, int i, DayOfWeek parameter, JdbcType jdbcType
    ) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public DayOfWeek getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return DayOfWeek.of(rs.getInt(columnName));
    }

    @Override
    public DayOfWeek getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return DayOfWeek.of(rs.getInt(columnIndex));
    }

    @Override
    public DayOfWeek getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return DayOfWeek.of(cs.getInt(columnIndex));
    }
}