mybatis processing result set mapping

Single-row result set mapping:

Interface method return value is defined as type Map, resultType sql statement attribute set to map to. This default value to the column name as key, as the column value.

That is receiving map <Strirng, Object>, corresponding to a collection of objects map the encapsulated query result (row of data corresponding to one object)

Multi-row result set mapping:

List <Map <String, Object >> receipt, check out the store multiple objects

If there are some special circumstances, such as the need to use the id value key, the data is encapsulated into a row value into the map object as it is necessary to use the following manner:

Note that this time the need to use a string to call the sql statement.

<select id="findAllUsers" resultType="User"> 
select id,name,gender from t_user 
</select>
@Test
public void test_findAllUsers(){

SqlSession sqlSession = null;
try {
sqlSession = MyBatisSqlSessionFactory.openSession();

Map<Integer, User> map = sqlSession.selectMap("com.briup.mappers.SpecialMapper.findAllUsers","id");

map.forEach((k,v)->System.out.println(k+" : "+v));

} catch (Exception e) {
e.printStackTrace ();
}
}

Here the id map value as the key, and each row of data is encapsulated into a User object value as the value, sqlSession.selectMap () can be used as the key column specified by us, encapsulated object as default value. That is key that we can specify, but only the current value of this data is encapsulated into objects.

Map<Integer, User> map = sqlSession.selectMap("com.briup.mappers.SpecialMapper.findAllUsers","id");

In fact, more than one core only code specified id is Key

 

 

mybatis the ResultHandler custom result set ResultSet

@Test
public void test_ResultHandler(){
final Map<Integer,String> map = new HashMap<Integer, String>(); 
SqlSession sqlSession = null;
try {
sqlSession = MyBatisSqlSessionFactory.openSession();


sqlSession.select("com.briup.mappers.SpecialMapper.findAllUsers", new ResultHandler<User>() {


@Override
public  void handleResult (The ResultContext <? the extends User> The ResultContext) {
 // Get When this data is encapsulated User object 
User User = resultContext.getResultObject (); 
 // encapsulated manner own requirements 
map.put (user. getId (), user.getName ()) ;
}
});


map.forEach((k,v)->System.out.println(k+" : "+v));


} catch (Exception e) {
e.printStackTrace ();
}


}

 

Guess you like

Origin www.cnblogs.com/Magic-Li/p/11687631.html