Retrieve data from database using Hibernate with S

2020-05-01 03:48发布

问题:

I'm trying to create a simple webapp with a search Page. I have implemented CRUD part and it's working. I'm new to coding. Having trouble with the search option. Error - "java.lang.NumberFormatException: For input string: "ISBN""

I need to get list of data as per the search criteria given.

Database table name = Items 
Columns 
* id - primary key 
* ISBN - String 
* title - String
category_id - String (I changed this from Int to String as I decided to use the book name instead, to make it simple. So this is not an ID its basically the book name so it's kept as a String)
* Author - String 
* publisher_id - String (same logic as category_id)
* price - FLOAT
* stock - INT
* photo_id - INT
DB DESC

ItemsController.java

@RequestMapping(value ="/search_1")
    public ModelAndView search_1(HttpServletRequest request, HttpServletResponse response) {

        String category_id = request.getParameter("category_id");
        String publisher_id = request.getParameter("publisher_id");

        List<Items> listItems2 = ItemsService.searchitems(category_id,publisher_id);

        ModelAndView model = new ModelAndView();
        model.setViewName("searchResult");
        model.addObject("items", listItems2);

        return model;
    }

IteamsDAO

package com.jwt.dao;

import java.util.List;

import com.jwt.model.Items;

public interface ItemsDAO {

    public void additems(Items items);

    public List<Items> getAllitems();

    public void deleteitems(Integer itemsId);

    public Items updateitems(Items items);

    public Items getitems(int itemsId);

    public List<Items> searchitems(String category_id, String publsiher_id);
}

ItemsDAOImpl

package com.jwt.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.jwt.model.Items;

@Repository ("ItemsDAO")
public class ItemsDAOImpl implements ItemsDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void additems(Items items) {
        sessionFactory.getCurrentSession().saveOrUpdate(items);

    }

    @SuppressWarnings("unchecked")
    public List<Items> getAllitems() {

        return sessionFactory.getCurrentSession().createQuery("from Items")
                .list();
    }

    @Override
    public void deleteitems(Integer itemsId) {
        Items items = (Items) sessionFactory.getCurrentSession().load(
                Items.class, itemsId);
        if (null != items) {
            this.sessionFactory.getCurrentSession().delete(items);
        }

    }

    public Items getitems(int itemsId) {
        return (Items) sessionFactory.getCurrentSession().get(
                Items.class, itemsId);
    }

    @Override
    public Items updateitems(Items items) {
        sessionFactory.getCurrentSession().update(items);
        return items;
    }

    @SuppressWarnings("unchecked")
    public List<Items> searchitems(String category_id, String publsiher_id) {

        return sessionFactory.getCurrentSession().createQuery("from Items E where E.category_id = category_id AND E.publisher_id=publisher_id")
                .list();

    }

}

Items.java

package com.jwt.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "items")
public class Items implements Serializable {

    private static final long serialVersionUID = -3465813074586302847L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column
    private String ISBN;

    @Column
    private String title;

    @Column
    private String category_id;

    @Column
    private String Author;


    @Column
    private String publisher_id;

    @Column
    private float price;

    @Column
    private int stock;

    @Column
    private int photo_id;



    public int getid() {
        return id;
    }

    public void setid(int id) {
        this.id = id;

    }

    public String getISBN() {
        return ISBN;
    }

    public void setISBN(String ISBN) {
        this.ISBN = ISBN;
    }

    public String gettitle() {
        return title;
    }

    public void settitle(String title) {
        this.title = title;
    }

    public String getcategory_id() {
        return category_id;
    }

    public void setcategory_id( String category_id) {
        this.category_id = category_id;
    }

    public String getAuthor() {
        return Author;
    }

    public void setAuthor(String Author) {
        this.Author = Author;
    }

  public String getpublisher_id() {
        return publisher_id;
    }

    public void setpublisher_id(String publisher_id) {
        this.publisher_id = publisher_id;
    }


     public float getprice() {
        return price;
    }

    public void setprice(float price) {
        this.price = price;
    }

     public int getstock() {
        return stock;
    }

    public void setstock(int stock) {
        this.stock = stock;
    }


     public int getphoto_id() {
        return photo_id;
    }

    public void setphoto_id(int photo_id) {
        this.photo_id = photo_id;
    }
}

ItemsService.java

package com.jwt.service;

import java.util.List;

import com.jwt.model.Items;

public interface ItemsService {

    public void additems(Items items);

    public List<Items> getAllitems();

    public void deleteitems(Integer itemsId);

    public Items updateitems(Items items);

    public Items getitems(int itemsId);

    public List<Items> searchitems(String category_id, String publsiher_id);


}

ItemsServiceImpl.java


package com.jwt.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jwt.dao.ItemsDAO;
import com.jwt.model.Items;

@Service
@Transactional
public class ItemsServiceImpl implements ItemsService {

    @Autowired
    private ItemsDAO itemsDAO;

    @Override
    @Transactional
    public void additems(Items items) {
        itemsDAO.additems(items);
    }

    @Override
    @Transactional
    public List<Items> getAllitems() {
        return itemsDAO.getAllitems();
    }

    @Override
    @Transactional
    public void deleteitems(Integer itemsId) {
        itemsDAO.deleteitems(itemsId);
    }

    public Items getitems(int itemsid) {
        return itemsDAO.getitems(itemsid);
    }

    public Items updateitems(Items items) {
        // TODO Auto-generated method stub
        return itemsDAO.updateitems(items);
    }

    public void setitemsDAO(ItemsDAO itemsDAO) {
        this.itemsDAO = itemsDAO;
    }

    @Override
    @Transactional
    public List<Items> searchitems(String category_id, String publsiher_id) {
        return itemsDAO.searchitems(category_id, publsiher_id);   
        }


}

Input search JSP page

search_1.jsp

<div align="center">
        <h1>Search Items</h1>


        <form action="search_1" method="get" modelAttribute="items">
        <table>
        <tr>
            <td>Category:</td>
            <td>
          <select  type="text" name="category_id">
            <option value="Book">Book</option>
            <option value="Audio Books">Audio Books</option>
            <option value="Videos">Videos</option>
            <option value="Music">Music</option>
          </select>
             </td>
        </tr>

        <tr>
            <td>Publisher ID:</td>
            <td>
          <select  type="text" name="publisher_id">
            <option value="Harper Collins">Harper Collins</option>
            <option value="Penguins">Penguins</option>
            <option value="Franciscan Media">Franciscan Media</option>
            <option value="Orbis">Orbis</option>
          </select>
             </td>
        </tr>



        <tr>
                <td colspan="2" align="center"><input type="submit" value="search"></td>
            </tr>

        </table>


        </form>


    </div>

search results will populate here

searchResult.jsp



      <div align="center">
        <h1>Book shop Inventory</h1>

        <table>

            <th>ISBN</th>
            <th>Title</th>
            <th>Category</th>
            <th>Author</th>
            <th>Publisher</th>
            <th>Price</th>
            <th>Stock</th>
            <th>Photo</th>


            <c:forEach var="items" items="${listItems2}">
                <tr>


                    <td>${items.ISBN}</td>
                    <td>${items.title}</td>
                    <td>${items.category_id}</td>
                    <td>${items.author}</td>
                    <td>${items.publisher_id}</td>
                    <td>${items.price}</td>
                    <td>${items.stock}</td>
                    <td>${items.photo_id}</td>


                </tr>
            </c:forEach>
        </table>
         </br>
        <input type="button" class="btn btn-info" value="Search Again" onclick="window.location.href='http://localhost:8080/SpringMVCHibernateCRUD_1/search'">
    </div>

Full error message


root cause

java.lang.NumberFormatException: For input string: "ISBN"
    java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    java.lang.Integer.parseInt(Integer.java:580)
    java.lang.Integer.parseInt(Integer.java:615)
    javax.el.ListELResolver.coerce(ListELResolver.java:163)
    javax.el.ListELResolver.getValue(ListELResolver.java:51)
    org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
    org.apache.el.parser.AstValue.getValue(AstValue.java:183)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
    org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
    org.apache.jsp.WEB_002dINF.pages.searchResult_jsp._jspService(searchResult_jsp.java:131)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1228)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1011)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

回答1:

You have to set the criteria as parameters to get result in ItemsDAOImpl

public List<Items> searchitems(String category_id, String publsiher_id) {

        return sessionFactory.getCurrentSession().createQuery("from Items E where E.category_id = :category_id AND E.publisher_id= :publisher_id")
                .setParameter("category_id", category_id)
                .setParameter("publisher_id", publsiher_id)
                .list();

    }

In your searchResult.jsp you are iterating over listItems2 but you added is attribute as items in your controller.

Change

 <c:forEach var="items" items="${listItems2}">

to

 <c:forEach var="items" items="${items}">

On an other note, please name the entities properly. Entity name should be Item and collection name should Items. But do that later, first try to fix the current problem.



回答2:

It was simple syntax issue at the end. @saifulislamplabon Answer fixed my Hibernate part and Error -" java.lang.NumberFormatException For input string: "ISBN" was causing because my JSP page had an error with <c:forEach tag. It was caused by the white space between <% @page. I corrected it to <%@page contentType="text/html" pageEncoding="UTF-8"%> and everything works fine now. Thanks for the support.