Hibernate - 如何在JSP表中显示对象列表?

时间:2016-02-19 04:20:25

标签: java mysql hibernate jsp

我有几个列的表,我想要表格将显示数据库中的所有行。但控制台说:javax.persistence.NonUniqueResultException: result returns more than one elements

这是一段代码:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("onlineshop");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Query query = entityManager.createNativeQuery("SELECT iduser FROM lastloggeduser ORDER BY idlastloggeduser DESC LIMIT 1");
    String s = query.getSingleResult().toString();


    if (s != null){
        Query selectAll = entityManager.createQuery("FROM Product WHERE iduser=:iduser");   
        selectAll.setParameter("iduser", s);
        System.out.println(s);
        Product p = (Product) selectAll.getSingleResult();

            Product product = new Product();
            product.setID(p.getID());
            product.setProduct(p.getProduct());
            product.setName(p.getName());
            product.setCompany(p.getCompany());
            product.setType(p.getType());
            product.setPrice(p.getPrice());

            products.add(product);


    }

JSP:

<c:forEach var="product" items="${products}">
            <tr>
                <td>${product.getID()}</td>
                <td><img src="${product.getProduct()}" /></td>
                <td>${product.getName()}</td>
                <td>${product.getCompany()}</td>
                <td>${product.getType()}</td>
                <td>${product.getPrice()}$</td>
                <td><form action="/OnlineShop/cart/cart.html?selectedItem=${product.getID()}"  method="post"><input type="submit" value="Delete"/></form></td>
            </tr>
            </c:forEach>

当我添加此内容时:

    selectAll.setMaxResults(1);

它工作正常,但在表中只出现一行,我应该怎么做才能显示所有行?

2 个答案:

答案 0 :(得分:0)

javax.persistence.NonUniqueResultException: result returns more than one elements

这表示该表对同一个iduser有多行。

    Product p = (Product) selectAll.getSingleResult();

尝试多个值,而不是期望单个结果。使用list()

List<Product> productsList = selectAll.list();

如果您不希望数据出现,请清理数据库以使每个iduser包含一行。

答案 1 :(得分:-1)

使用Resultset执行查询,然后遍历Resultset逐个添加产品。