How to connect a ResultHandler in MyBatis Mapper XML
Asked Answered
S

2

4

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?

Sexist answered 9/2, 2015 at 15:51 Comment(0)
P
10

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();
}
Plagiary answered 6/3, 2015 at 11:32 Comment(3)
As I have written above I am searching for how to use a custom ResultMapper in the XML-way, not in the javacode-waySexist
You asked how to use a ResultHandler - this answer is correct.Swanky
Can this also be called as a @Result with @Many?Flaunty
O
0

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();
    }
Oyez answered 2/5 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.