Search code examples
struts2iteratorhibernate3multiple-value

Get multiple values from strut2 iterator


I am new to struts. I dont know exactly if my solution for my problem is correct or not. My problem is I have two tables as shown below

relation tables

I would like to create an HTML table based on the above tables, showing the fields, name of group, id of group, and name of sub group and Id of subgroup. I tried to use list and iterator. But am not able to get both the values(both name and id)

inside class

public List getName() {
    return namesHead;
}

public void setName(List name) {
    this.namesHead = name;
}

public String listModules() {
    SessionFactory factory = HibernateLoginUtil.getFactory();
    Session session = factory.openSession();
    Query q1 = session.createQuery ("select id,name FROM TableUsrModuleGroup WHERE stat='active'");
    for(Iterator it = q1.iterate() ; it.hasNext() ;) {
         Object row[] = (Object[]) it.next();
         namesHead.add (row[1]); //put the name
    }   
    return SUCCESS;
}

in JSP page

<table>
  <s:iterator  status="status" value="namesHead" >   
  <tr><td><s:property/></td></tr>
  </s:iterator>
</table>

(only name of group can i get from the above code, I need to display group name, group Id, and name of sub group and Id of sub group)


Solution

  • If you are using Hibernate, I think that the simplest option is to map the two classes and then recover both with a HQL query. For instance:

    public class Group {
        @OneToMany (mappedBy = "group", fetch = FetchType.LAZY)
        private Collection <SubGroup> subgroup;
        ... // Rest of the class, getters and setters
    }
    
    public class SubGroup {
        @ManyToOne (fetch = FetchType.LAZY)
        private Group group;
        ... // Rest of the class, getters and setters
    }
    

    Then you have to make this HQL query to get the Group class:

    Query q = session.createQuery ("FROM SubGroup");
    List<SubGroup> subgroups = (List<SubGroup>) q.list();
    

    Then you set an attribute with the subgroups in the Action and then you access to them in the jsp.

    <table>
       <s:iterator  value="subgroups" >   
       <tr>
          <td>
              <s:property value="name"/>
          </td>
    
          <td>
              <s:property value="id"/>
          </td>
    
          <td>
              <s:property value="group.name"/>
          </td>
    
          <td>
              <s:property value="group.id"/>
          </td>
       </tr>
       </s:iterator>
    </table>
    

    I hope it helps =)