Search code examples
javamybatisspring-mybatis

Java MyBatis mutate returned object / custom mapper


Give a SQL schema of:

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

I would like a mapper like:

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();
}

So I can do this:

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

Not sure how to do this other than after personMapper.getPersons() to manipulate the results.


Solution

  • I found the answer, you can set the result TypeHandler:

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

    Then define the 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));
        }
    }