Hiberate查询结果集以及显示以及巧方法

 得到结果集的方法:
public Iterator searchUser(String name, String phone, String address) {
  String strsql=new String("from Addressbook where ");
  if(!name.equals(""))
    strsql=strsql+"name like '"+name+"%' and";
  if(!phone.equals(""))
   strsql=strsql+"phone like '"+phone+"%' and";
  if(!address.equals(""))
   strsql=strsql+"address like '"+address+"%'";
  else
   strsql=strsql.substring(0,strsql.length()-3);
  strsql=strsql+"order by ID";
  System.out.println(strsql);
  Query q=this.session.createQuery(strsql);
  System.out.println("end");
  
  Iterator iter =q.iterate();
  
  return iter;
 }
得到结果集的一个巧方法:
public Iterator searchUser(String name, String phone, String address) {
   Addressbook book=new Addressbook();
  if(!name.equals(""))
  {
   book.setName(name);
  }
  if(!address.equals(""))
  {
   book.setAddress(address);
  }
  if(!phone.equals(""))
  {
   book.setPhone(phone);
  }
  Criteria criteria=session.createCriteria(Addressbook.class);
  System.out.println(Addressbook.class);
  criteria.add(Example.create(book));
  List list=criteria.list();
  Iterator iter=list.iterator();
  return iter;
 }
在Action的处理
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  SearchForm searchForm = (SearchForm) form;// TODO Auto-generated method stub
  ActionMessages errors=new ActionMessages();
  String name=searchForm.getName();
  String phone=searchForm.getPhone();
  String address=searchForm.getAddress();
  Iterator iter=DAOFactory.getAddressbookDAOInstance().searchUser(name, phone, address);
  System.out.println("begin");
  
  if(iter.hasNext())
   {request.setAttribute("name",name );
   request.setAttribute("phone", phone);
   request.setAttribute("address", address);
   System.out.println("DIS");
   return mapping.findForward("display");}
  else
  {
   errors.add("search",new ActionMessage("search2.error"));
   saveMessages(request,errors);
   return (new ActionForward(mapping.getInput()));
  }
 }
在JSP页面的显示
<table border=1>
    <tr>
    <td>ID</td>
    <td>名字</td>
    <td>电话</td>
    <td>住址</td>
    </tr>
    <%
    String name=request.getAttribute("name").toString();
    String phone=request.getAttribute("phone").toString();
    String address=request.getAttribute("address").toString();
    Iterator iter=DAOFactory.getAddressbookDAOInstance().searchUser(name,phone,address);
 
    while(iter.hasNext())
    {Addressbook result=(Addressbook)iter.next();
    %>
    <tr>
    <td widt><%=result.getId() %></td>
    <td><%=result.getName() %></td>
    <td><%=result.getPhone() %></td>
    <td><%=result.getAddress() %></td>
    </tr>
    <%}
     %>
    </table>

你可能感兴趣的:(Hibernate,jsp)