Search code examples
javaselectjakarta-eehtml-tablejpql

Transmit data into jsp from 2 tables in one query


I have a two tables( Entity classes) and need select from both and transmit result into jsp page.

My Entity for Balance:

 @Entity
    @NamedQuery (name = "findLastFiveTransaction",
    query = "select c, b from Categorietype c, Balance b  where c.user = :user and b.user = :user")
    public class Balance implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String id;

    private BigDecimal sum;
    @Column(name="Description")
    private String descrip;

My Entity for Categorietype:

@Entity
public class Categorietype implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String id;

    private String name;

    //bi-directional many-to-one association to Balance
    @OneToMany(mappedBy="categorietype")
    private List<Balance> balances;

    //bi-directional many-to-one association to User
    @ManyToOne
    @JoinColumn(name="UserID")
    private User user;

Method in EJB Class:

 public List getUserTransaction(User user) {
    return em.createNamedQuery("findLastFiveTransaction").setParameter("user", user).getResultList();
    }

My code on jsp page:

<table border="1">

  <tr>
    <th>Sum</th>
    <th>Descrip</th>
    <th>Name</th>
  </tr>
<c:forEach items="${result}" var="r">
  <tr>
    <td> ${r.sum} </td>
    <td> ${r.descrip} </td>
    <td> ${r.name} </td>
  </tr>
</c:forEach>
</table> 

In such variant I getting messages

org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "sum"

My problem is how parse data transferred into jsp page. I transmit data from my servlet:

List result = balance.getUserTransaction(user);
request.setAttribute("result", result );
request.getRequestDispatcher("finance.jsp").forward(request, response);

How I must to do correct this or show me where I can read this?


Solution

  • I found solution of this problem. Correct query

    select b from Categorietype c, Balance b  where c.user = :user and b.user = :user
    

    and on jsp page change ${r.name} to r.typecategory.sum

    <table border="1">
    
      <tr>
        <th>Sum</th>
        <th>Descrip</th>
        <th>Name</th>
      </tr>
    <c:forEach items="${result}" var="r">
      <tr>
        <td> ${r.sum} </td>
        <td> ${r.descrip} </td>
        <td> ${r.typecategory.name} </td>
      </tr>
    </c:forEach>
    </table> 
    

    PS I change my query to

    select b.id as id, b.sum, b.description, t.name from Balance b join b.typecategory t where b.user = :user and b.typecategory = t and b.status = :status
    

    It's more correctly