Search code examples
ibatismybatis

Ibatis/MyBatis select dynamically without need to create any Pojo / Mapper


Is there any way to select/update/delete dynamically using Ibatis/MyBatis?

When I say "dynamically" it means I don't want to create any POJO/DataMapper at all.

Any URL example would be welcomed.


Solution

  • Yes, just set the resultType attribute to map and the table data will be placed into a HashMap of column names to values. If the query returns more than 1 row, the mapped rows will be put into a List. If you want to select a single column, you can get just that value (as String, int, etc) or as a list.

    <select id="test1" resultType="map">select * from user</select>
    <select id="test2" resultType="map" parameterType="int">
      select * from user where id=#{value}</select>
    <select id="test3" resultType="string">select name from user</select>
    ...
    // returns a list of maps
    List test = sqlSession.selectList("test1");
    
    // returns a single map
    Object map = sqlSession.selectOne("test2", 0);
    
    // returns a list of strings
    List names = sqlSession.selectList("test3");
    

    This applies to MyBatis 3; I think you can do something similar in iBatis 2.