Mahatma_Fatal_Error
Mahatma_Fatal_Error

Reputation: 779

How to connect a ResultHandler in MyBatis Mapper XML

I found several examples how to connect a custom ResultHandler to a MyBatis Query:

e.g. https://code.google.com/p/mybatis/wiki/ResultHandlerExample

Unfortunately the ResultHandler given in the example never gets invoked. (As the last comment already stated)

So I searched for a solution and found this: MyBatis - ResultHandler is not invoked

But this does not quite fit to my problem since I'm using MyBatis the xml-style way rather than the API-style way. So in my case I have no

SqlSession session = MyBatisConnectionFactory.getSqlSessionFactory().openSession(true);

Is there a way to connect my custom handler in the xml file, for example the <resultMap /> oder <select /> node?

Upvotes: 4

Views: 11774

Answers (2)

uncle bob
uncle bob

Reputation: 680

you can define mapper like this:

public interface YourMapper {
    void list(@Param("param1") Object param1, ResultHandler handler);
}

and in xml:

<select id="list" parameterType="map" resultType="map">
        SELECT *
        FROM
        <include refid="tableName"/>
        WHERE param1=#{param1}
    </select>

here is your resultHandler:

public class CustomResultHandler implements ResultHandler<List<CustomResult>> {

    @Getter
    private List<CustomResult> customResults;

    
    @Override
    public void handleResult(ResultContext rc) {
        Map<String,Object> results = (Map<String,Object>)rc.getResultObject();
        ///this func is called once on each row found, let store result to `customResults`
    }
}

on caller will look like:

public List<CustomResult> list(String param1) {
        CustomResultHandler resultHandler = new CustomResultHandler();
        mapper.list(param1,resultHandler);
        return resultHandler.getCustomResults();
    }

Upvotes: 0

ocmwdt
ocmwdt

Reputation: 116

You can define method with ResultHandler in your mapper:

public interface YourMapper {
    void getObjects(@Param("param1") Object param1, ResultHandler handler);
}

Then you can use it:

List<Object> getObjects(object param1) {
    YourResultHandler resultHandler = new YourResultHandler();
    yourMapper.getObjects(param1, resultHandler);
    return resultHandler.getResults();
}

Upvotes: 10

Related Questions