Manipulating a List inside a foreach in a view

Asked

Viewed 895 times

1

I have a doubt that should be simple to solve, but I’m not able to develop a logic, or even may be doing it the wrong way.

Well, I have a table in which I go through a table called "categories" within this table I have a relationship with another called "destinations" as you can notice below in the bean:

Destination.java

@Entity
@Table(name="destination")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Destination.findAll", query="SELECT d FROM Destination d")
public class Destination implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_destination")
    private Long idDestination;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @Column(name="appear_website")
    private Boolean dtAppearWebsite;

    @Lob
    @Column(name="description")
    private String dtDescription;

    @Column(name="highlight_website")
    private Boolean dtHighlightWebsite;

    @Column(name="name")
    private String dtName;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_streetview")
    private StreetView streetView;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_video")
    private Video video;

    @ManyToOne(cascade=CascadeType.REFRESH)
    @JoinColumn(name="fk_category")
    private Category categories;


    //Getters and Setters

Category.java

@Entity
@Table(name="category")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_category")
    private Long idCategory;

    @Column(name="ct_active")
    private int ctActive;

    @Column(name="ct_name")
    private String ctName;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @OneToMany(mappedBy="categories")
    private Set<Destination> destination;

    //Getters and Setters

Right! In my view I have a field in which I have displayed the number of destinations linked to each category:

<c:forEach items="${category}" var="c">
    <tr>
        <td><a href="editCategory?id=${c.idCategory}">${c.ctName}</a></td>
        <!-- Campo no qual o numero de destinos é exibido por categoria-->
        <td>${categoryHasDestination}</td>
        <c:choose>
            <c:when test="${c.ctActive=='1'}">
                <td><span class="label label-success">Ativo</span></td>
            </c:when>
            <c:otherwise>
                <td><span class="label label-warning">Desativo</span></td>
            </c:otherwise>
        </c:choose>
    </tr>
</c:forEach>

So, I created a method in which returns the categories and also a list of the number of linked destinations in each category.

@RequestMapping("category")
public String getMenuCategory(Model mv) {
    List<Category> category = dashboardFacade.getCategoryList();
    List<Integer> size = new ArrayList<Integer>();

    for (Category categories : category) {
        Set<Destination> destinationList = categories.getDestination();
        int s = destinationList.size();
        size.add(s);
    }

    /Retorna uma lista com o numero de destinos para cada categoria
    mv.addAttribute("categoryHasDestination", size);

    //Me retorna todas as categorias
    mv.addAttribute("category", category);
    return "category/categoryList";
}

The problem is that in my view I have a foreach, IE, for each record the list is returned and not the number itself. The image below illustrates what I mean:

inserir a descrição da imagem aqui

I thank you all for your help

Hug!

  • Have you tried using the attribute var of forEach to index the list categoryHasDestination? I believe I would ${categoryHasDestination[i]} being i the var of foreach. The way utluiz quoted is more correct from the OO point of view.

  • Hi Wakin. Yes the alternative is the right one, but I’m using multi-tenant and it causes some problems if I do it this way. Could you tell me more about your alternative? Thank you very much

  • Taking a closer look at the documentation of forEach, is the variable varStatus which provides the index of the item in the list. I will elaborate an answer to see if it solves your problem.

2 answers

0


Create a method getDestinationSize in your class Category that returns the size of the attribute destination.

Then in your JSP, just access the method ${c.destinationSize}.

  • utluiz, I did this way, but as I’m using multi tenant it gives me some errors that at the moment is complicated to solve. I would like some alternative in my controller so that I can pass as an attribute to the view. Thank you so much for the help.

  • @Joãomanolo I don’t understand what the problem with multi tenant. The attribute is in the model and its scope is the request, it will not affect other users.

  • It actually worked, yes! What happened is that in my Destination mapping, it was the LAZY standard. I ended up putting as EAGER and everything worked perfectly. The multi tenant question, and that whenever there is a query in the bank I have to pass the tenant_id to know with which tenant I am handling. Soon with Azy he gave problem because I did not pass the current tenant. As there will be few registered records I believe it will not burden much the performance of my system. Thank you very much for your help hug and success!

  • @Joãomanolo Legal, I didn’t know this question of Lazy, but it’s interesting to know. Hug!

  • 1

    just a caveat I forgot to comment on. Your blog and beast! I was taking a look here and the articles are ball show. You can be sure that I will use many of the published articles.Congratulations!!!

  • @Joãomanolo If you have suggestions you can write to me there :D

Show 1 more comment

0

Using the forEach of jstl exists the attribute varStatus exposing an object of the type javax.servlet.jsp.jstl.core.LoopTagStatus in the iteration scope, which provides some data about the object being iterated.

In that case I’m using the index to index your list of categoryHasDestination to get the data you need.

<c:forEach items="${category}" var="c" varStatus="status">
    <tr>
        <td><a href="editCategory?id=${c.idCategory}">${c.ctName}</a></td>
        <!-- Campo no qual o numero de destinos é exibido por categoria-->
        <td>${categoryHasDestination[status.index]}</td>
        <c:choose>
            <c:when test="${c.ctActive=='1'}">
                <td><span class="label label-success">Ativo</span></td>
            </c:when>
            <c:otherwise>
                <td><span class="label label-warning">Desativo</span></td>
            </c:otherwise>
        </c:choose>
    </tr>
</c:forEach>

To see the other attributes of a look at the documentation of LoopTagStatus

  • Hi Wakim. Thank you for your contribution. In fact it finally worked out the suggestion of our fellow utluiz. But really cool this feature of Looptagstaus. I ended up reading some information and found this approach very interesting. A hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.