1

I need to retrieve items from database and show them on browser in a specific order.

I have two forEach loops, first one loops through products of factory object and second one loops through different types of each product.

I need to show ordered results based on price of each type of product but using the following code every time that I refresh the page results will be shown in different order.

I need to have the results sorted, it does not matter if get sorted while retrieving them using Hibernate or while showing on browser.

 <c:forEach var="product" items="${factory.products}">
        <table border="2">
             <thead><tr><td>ID</td><td>Type</td><td>Amount</td></tr></thead>
             <tbody>
                   <c:forEach var="ptype" items="${product.types}">  

                        <tr>
                            <td>${ptype.id}</td>
                            <td>${ptype.name}</td>
                            <td>${ptype.price}</td>
                        </tr>

                   </c:forEach>
            </tbody>
        </table>
    <hr/>
 </c:forEach>

I am retrieving the results as following

Factory factory = (Factory) session.createCriteria(factory.class, "fac")
                        .createAlias("fac.products", "pro")
                        .createAlias("pro.types", "types")
                        .setFetchMode("pro", FetchMode.SELECT)
                        .add(Restrictions.eq("fac.id", facId))
                        .addOrder(Property.forName("types.price").asc())
                        .list().get(0);
J888
  • 1,944
  • 8
  • 42
  • 76

1 Answers1

1

As well as you sorting data in the database you should create a variable that holds the state of the order. Usually two variables are used: one for the column index, another for the column order (ascending|descending). Between action calls to save these variables you could use a parameter, or session map, or use the scope interceptor to set the session scope of the order variable. Switch the order

.addOrder(order.equals("asc")?
  Property.forName("types.price").asc():Property.forName("types.price").desc())   
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • would you explain more about this sentence , I do not get it(Btw action calls to save ....) – J888 Nov 25 '13 at 01:19
  • How could I know what you didn't get? Ask a question, may be [this](http://stackoverflow.com/a/17107828/573032), or [that](http://stackoverflow.com/a/18462744/573032), or [those](http://stackoverflow.com/q/17244036/573032) better explain you. – Roman C Nov 25 '13 at 08:48