简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM