Iterate list of Objects in Ibatis

后端 未结 3 1647
难免孤独
难免孤独 2020-12-30 12:46

I have a list of object where I want to iterate and access a particular field in ibatis sql.

Ex.

public Class Student
{
String id;
String name;
}
<         


        
相关标签:
3条回答
  • 2020-12-30 13:32

    Try something like:

    <select id="StudentsQry" parameterClass="list">
    
    select * from STUDENTS where 
    ( id, name ) in 
            <iterate open="(" close=")" conjunction="," >
                    ( #[].id# , #[].name# )
            </iterate>
    
    <select>
    

    where id and name are fields of Student class and my parameterClass is List<Student>.

    Worked for me.

    The sql formed dynamically will look like:

    select * from STUDENTS where ( id, name ) in ( (1,'a'), (2,'b') )
    
    0 讨论(0)
  • 2020-12-30 13:39

    A simple example.

    <select id="selectFewStudents" resultMap="MyMap" parameterClass="list">
        select * from student_table where student_id in
        <iterate open="(" close=")" conjunction=",">
           #[]#
        </iterate>
    </select>
    

    Refer iBatis documentation for more info.

    As Sylar pointed out, the java equivalent would be

    <select id="selectFewStudents" resultType="MyMap">
      select * from student_table where student_id in
       <foreach item="currentRow" index="rowNum" collection="list" open="(" separator="," close=")">
        #{currentRow}
      </foreach>
    </select>
    

    iBatis allows you to variables item and index which you can use inside the loop.

    0 讨论(0)
  • 2020-12-30 13:48

    The foreach-tag is what you are looking for. Example:

    <select id="selectPostIn" resultType="domain.blog.Post">
      SELECT *
       FROM POST P
       WHERE ID in
       <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
       </foreach>
    </select>
    

    See the user guide for more info, chapter "dynamic sql".

    By the way, iBatis is no longer developed and is frozen, it is now called "MyBatis" and the whole developer team moved away from Apache to the new MyBatis home.

    0 讨论(0)
提交回复
热议问题