【问题标题】:Can´t retrieve data from database to jsp using Hibernate无法使用 Hibernate 将数据从数据库检索到 jsp
【发布时间】:2016-02-17 14:36:47
【问题描述】:

我试图在从我的 Oracle 数据库中检索数据的表中显示数据,但它不会显示。

这是我正在使用的代码。

Servlet 列出数据:

package org.sistemamedico.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sistemamedico.db.Conexion;

@WebServlet("/ServletListarMedicamento.do")
public class ServletListarMedicamento extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {
    RequestDispatcher despachador = null;
    req.setAttribute("listaMedicamento", Conexion.getInstancia().listar("From Medicamento"));
    despachador = req.getRequestDispatcher("sistemamedico/farmacia.jsp");
    despachador.forward(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(req, resp);
}
}

使用列表方法连接数据库:

package org.sistemamedico.db;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class Conexion {
private SessionFactory sesion;
private static Conexion instancia;
public static synchronized Conexion getInstancia(){
    return (instancia==null)?new Conexion():instancia;
}
public Conexion(){
    try {
        sesion=new Configuration().configure().buildSessionFactory();
    } catch (Throwable e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}
public void closeSession()throws HibernateException {
    try {
        if (sesion.isClosed()==false | sesion.getCurrentSession().isOpen()) {
            sesion.close();
            sesion.getCurrentSession().close();
        }
    } catch (HibernateException ex) {
        throw new HibernateException(ex);
    }
}

public List<Object> listar(String consulta){
    Session miSesion=sesion.getCurrentSession();
    List<Object> lista=null;
    miSesion.beginTransaction();
    lista=miSesion.createQuery(consulta).list();
    miSesion.getTransaction().commit();
    return lista;
}
public List<Object> autenticarUsuario(String nick,String contraseña){
    Session miSesion=sesion.getCurrentSession();
    List<Object> lista=null;
    miSesion.beginTransaction();
    lista=miSesion.createQuery("From Usuario u where u.nick='"+nick+"' and contraseña='"+contraseña+"'").list();
    miSesion.getTransaction().commit();
    return lista;
}
public void agregar (Object agregar){
    Session session=sesion.getCurrentSession();
    session.beginTransaction();
    session.save(agregar);
    session.getTransaction().commit();  
}
public Object buscar(Class<?> clase,int id){
    Session session=sesion.getCurrentSession();
    session.beginTransaction();
    Object obj=session.get(clase, id);
    session.getTransaction().commit();
    return obj;
}
public Object buscar(Class<?> clase,String id){
    Session session=sesion.getCurrentSession();
    session.beginTransaction();
    Object obj=session.get(clase, id);
    session.getTransaction().commit();
    return obj;
}
}

我在 JSP 中的表格:

<table class="table table-hover">
              <thead>
                <tr>
                  <th>Nombre</th>
                  <th>Descripcion</th>
                  <th>Proveedor</th>
                  <th>Fecha Vencimiento</th>
                  <th>Precio</th>
                </tr>
               </thead>
               <tbody>
                  <c:forEach items="${listaMedicamento}" var="medicamento">
                    <tr>
                        <td>${medicamento.getNombre()}</td>
                        <td>${medicamento.getDescripcion()}</td>
                        <td>${medicamento.getIdProveedor().getNombre()}</td>
                        <td>${medicamento.getFechaVencimiento()}</td>
                        <td>${medicamento.getPrecio()}</td>
                    </tr>
                 </c:forEach>
                </tbody>
            </table>

我已经放了 taglib,所以 c:foreach 可以工作,但它不会显示任何数据。

【问题讨论】:

  • 您确定您的 SQL“From”语句正在检索数据吗?

标签: java hibernate jsp


【解决方案1】:

当我使用&lt;c:forEach&gt; 时,我使用&lt;c:out&gt; 来显示每个单元格。看看这是否有效。

<tbody>
    <c:forEach items="${listaMedicamento}" var="medicamento">
                <tr>
                    <td><c:out value="${medicamento.getNombre()}"/></td>
                    <td><c:out value="${medicamento.getDescripcion()}"/></td>
                    <td><c:out value="${medicamento.getIdProveedor().getNombre()}"/></td>
                    <td><c:out value="${medicamento.getFechaVencimiento()}"/></td>
                    <td><c:out value="${medicamento.getPrecio()}"/</td>
                </tr>
      </c:forEach>
</tbody>

【讨论】:

    【解决方案2】:

    Step1:请在Servlet类中打印出来试试看db中的list数据是否正确。
    Step2:如果数据正确,请检查列表中的对象类型/结构并验证您是否在 JSP 中正确地迭代它。
    Step3:如果列表为空,我们必须修改查询并进一步调试。
    示例:列表 listFromDb = Conexion.getInstancia().listar("From Medicamento"); System.out.println("db 中的数据是:"+listFromDb); req.setAttribute("listaMedicamento", listFromDb);

    【讨论】:

    • 谢谢,尝试在控制台打印出列表,但没有显示任何内容。
    • 请先验证表中的记录数,因为列表为空。请在 Conexion 类中添加 getCount 方法并尝试查看 table-Medicamento 中的记录数。示例: ( (Integer) session.createQuery("select count(*) from Medicamento").iterate().next() ).intValue()
    • 您是否能够使用选择计数查询来验证表中的记录数?
    猜你喜欢
    • 2016-05-17
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2019-06-14
    • 2014-04-20
    相关资源
    最近更新 更多