PersonMapper.java公共接口 PersonMapper {光标选择所有人();}MyService.javaPersonMapper personMapper = ...;试试 (Cursorpersons = personMapper.selectAllPersons()) {对于(人:人){//处理一个人}}I need to dump data from a table in oracle to elasticsearch(100 Million record),My memory limit of JVM is 256M, I use the following code and config to get the data from oracle (mybatis + spring):the interface:package com.fudy.mapper;import java.util.List;import com.fudy.domain.Person;public interface PersonMapper { List<Person> selectAllPerson();}the <?ApplicationContext.<?My junit test:package com.fudy.mapper;import java.util.List;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.fudy.domain.Person;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"/ApplicationContext.you can see from the junit test, Mybatis will return the whole list of the result and this will cause out of memory issue. After google it, I find the ResultHandler may solve the problem, But I can't find a working demo. 解决方案 There are two options:use ResultHandlersince 3.4.1 use CursorResultHandlerThat is how you can use custom ResultHandler:PersonMapper.<mapper namespace="com.fudy.mapper.PersonMapper"> <resultMap type="com.fudy.domain.Person" id="PersonAlias"> <id column="ID" property="id" /> <result column="NAME" property="name" /> </resultMap> <select id="selectAllPerson" resultMap="PersonAlias"> SELECT * FROM person </select></mapper>PersonMapper.javapublic interface PersonMapper { void selectAllPersons(ResultHandler handler);}MyService.javaclass PersonResultHandler implements ResultHandler { @Override public void handleResult(ResultContext context) { Person person = (Person)context.getResultObject(); // process person here }};PersonResultHandler handler = new PersonResultHandler();PersonMapper personMapper = ...;personMapper.selectAllPersons(handler);CursorStarting from mybatis 3.4.1 you can return Cursor which is Iterable and can be used like this (under condition that result is ordered, see above Cursor API java doc for details):PersonMapper.javapublic interface PersonMapper { Cursor<Person> selectAllPersons();}MyService.javaPersonMapper personMapper = ...;try (Cursor<Person> persons = personMapper.selectAllPersons()) { for (Person person : persons) { // process one person }} 这篇关于Mybatis在spring中使用 上岸,阿里云!
07-22 09:30