Ver Mensaje Individual
  #1 (permalink)  
Antiguo 01/03/2013, 10:50
gt_int
 
Fecha de Ingreso: febrero-2013
Mensajes: 50
Antigüedad: 11 años, 1 mes
Puntos: 0
Valor null en Struts2

Que tal a todos, en una aplicación que estoy desarrollando en Struts2-Hibernate estoy teniendo problemas. Ahora mismo tengo 2 objetos, que son: Categoría y Producto. Una Categoría está compuesta por 1 o más Productos.

Entonces hay una parte de la aplicación donde aparece el listado con las categorías, el usuario elige una categoría y le aparece el listado con los productos asociados a esa categoría.

Pues bien hago una consulta para que me devuelva un listado con los productos asociados a una categoria, desde HibernateManager compruebo con debug que efectivamente me devuelve ese listado, pero cuando estoy en la clase Action de Producto donde hago referencia a esa consulta pues ahí en el listado me devuelve un null, no entiendo muy bien porqué sucede.

Voy a poner el código:


listarCategorias.jsp

Código JSP:
Ver original
  1. <%@ page contentType="text/html; charset=UTF-8"%>
  2. <%@ taglib prefix="s" uri="/struts-tags"%>
  3. <html>
  4. <head>
  5.     <title>Categorias</title>
  6. </head>
  7. <body>
  8.  
  9. <s:actionerror/>
  10. <s:form action="seleccionarProductos" method="post">
  11. <s:select label="Categoria" list="categoriaList" name="nombreCategoria"/>
  12. <s:submit value="Ver Productos" align="center"/>
  13. </s:form>
  14.  
  15. <s:iterator value="productoList" var="producto">
  16.     <tr>
  17.         <td><s:property value="nombre"/></td>
  18.     </tr>
  19. </s:iterator>
  20. </body>
  21. </html>


struts.xml
Código XML:
Ver original
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE struts PUBLIC
  3.    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4.    "http://struts.apache.org/dtds/struts-2.0.dtd">
  5.  
  6. <struts>
  7.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  8.     <constant name="struts.devMode" value="false" />
  9.  
  10.     <package name="default" extends="struts-default" namespace="/">
  11.  
  12.      
  13.        
  14.          <action name="seleccionarProductos" class="web.ProductoAction" method="seleccionarProductos">
  15.             <result name="success" type="chain">listarCategorias</result>
  16.             <result name="input" type="chain">index</result>
  17.             <result name="error" type="chain">listarCategorias</result>
  18.         </action>
  19.  
  20.  
  21.         <action name="index" class="web.CategoriaAction">
  22.             <result name="success">/index.jsp</result>
  23.         </action>
  24.        
  25.        
  26.         <action name="listarCategorias" class="web.CategoriaAction">
  27.             <result name="success">/listarCategorias.jsp</result>
  28.         </action>
  29.     </package>
  30. </struts>




ProductoAction.java
Código JAVA:
Ver original
  1. package web;
  2.  
  3. import java.util.List;
  4. import com.opensymphony.xwork2.ActionSupport;
  5.  
  6. import database.entity.Categoria;
  7. import database.entity.Producto;
  8. import database.manager.CategoriaManager;
  9. import database.manager.ProductoManager;
  10.  
  11.  
  12. public class ProductoAction extends ActionSupport {
  13.  
  14.     private static final long serialVersionUID = 9149826260758390091L;
  15.     private Producto producto;
  16.     private List<Producto> productoList;
  17.     private Long id;
  18.  
  19.     private String nombreCategoria;
  20.     private List<Categoria> categoriaList;
  21.     private CategoriaManager categoriaController;
  22.  
  23.    
  24.     private ProductoManager productoManager;
  25.  
  26.     public ProductoAction() {
  27.         productoManager = new ProductoManager();
  28.         categoriaController = new CategoriaManager();
  29.     }
  30.  
  31.    
  32.    
  33.     public String seleccionarProductos() {
  34.         Categoria c = (Categoria) categoriaController.getElementByNombre(nombreCategoria);
  35.         this.productoList = productoManager.getListadoPiezasDeCategorias(c.getId());
  36.         return SUCCESS;
  37.     }
  38.    
  39.     public String execute() {
  40.         this.categoriaList = categoriaController.getList();
  41.  
  42.         System.out.println("execute called");
  43.         return SUCCESS;
  44.     }
  45.    
  46.     public String add() {
  47.         System.out.println(getProducto());
  48.         try {
  49.             Categoria c = (Categoria) categoriaController.getElementByNombre(nombreCategoria);
  50.             this.producto.setCategoria(c);
  51.            productoManager.create(getProducto());
  52.         } catch (Exception e) {
  53.             e.printStackTrace();
  54.         }
  55.         this.productoList = productoManager.getList();
  56.         return SUCCESS;
  57.     }
  58.  
  59.     public String delete() {
  60.         productoManager.delete(getId());
  61.         return SUCCESS;
  62.     }
  63.  
  64.     public Producto getProducto() {
  65.         return producto;
  66.     }
  67.  
  68.     public List<Producto> getProductoList() {
  69.         return productoList;
  70.     }
  71.  
  72.     public void setProducto(Producto producto) {
  73.         this.producto = producto;
  74.     }
  75.  
  76.     public void setProductoList(List<Producto> productosList) {
  77.         this.productoList = productosList;
  78.     }
  79.  
  80.     public Long getId() {
  81.         return id;
  82.     }
  83.  
  84.     public void setId(Long id) {
  85.         this.id = id;
  86.     }
  87.  
  88.     public String getNombreCategoria() {
  89.         return nombreCategoria;
  90.     }
  91.  
  92.     public void setNombreCategoria(String nombreCategoria) {
  93.         this.nombreCategoria = nombreCategoria;
  94.     }
  95.  
  96.     public List<Categoria> getCategoriaList() {
  97.         return categoriaList;
  98.     }
  99.  
  100.     public void setCategoriaList(List<Categoria> categoriaList) {
  101.         this.categoriaList = categoriaList;
  102.     }
  103.    
  104.    
  105. }


HibernateManager.java
Código JAVA:
Ver original
  1. package database.common;
  2.  
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.  
  6. import org.hibernate.Query;
  7. import org.hibernate.Session;  
  8. import org.hibernate.criterion.Projections;  
  9. import org.hibernate.criterion.Restrictions;  
  10.  
  11. public abstract class HibernateManager {  
  12.  
  13.    protected Object myClass = new Object(); // tipo de objeto  
  14.    protected String TABLE = ""; // nombre de la tabla  
  15.  
  16.  
  17.     public Object getElementByNombre(String nombre) {
  18.         Object obj = new Object();
  19.         // obtener la sesion actual
  20.         Session session = getSession();
  21.         try {
  22.             // comenzar la transaccion
  23.             session.beginTransaction();
  24.             // cargar objeto por clave
  25.             obj = session.createCriteria(myClass.getClass())
  26.                     .add(Restrictions.eq("nombre", nombre)).uniqueResult();
  27.             // confirmar transaccion
  28.             session.getTransaction().commit();
  29.         } catch (Exception e) {
  30.             System.out.println("Error en getElementById: " + e);
  31.             // deshacer transaccion
  32.             this.rollback();
  33.         }
  34.         return obj;
  35.     }
  36.  
  37.    
  38.    /**  
  39.     * Obtener la lista de registros para una entidad  
  40.     * @return  
  41.     */  
  42.    public List getList(){  
  43.        // obtener la sesion actual  
  44.        Session session = getSession();  
  45.        List result = new ArrayList();  
  46.        try {  
  47.            // comenzar la transaccion  
  48.            session.beginTransaction();  
  49.            // obtener la lista de eventos  
  50.            result = session.createCriteria(myClass.getClass()).list();  
  51.            // confirmar transaccion  
  52.            session.getTransaction().commit();  
  53.        } catch (Exception e) {  
  54.            System.out.println("Error en getList: " + e);  
  55.            // deshacer transaccion  
  56.            this.rollback();  
  57.        }  
  58.        return result;  
  59.    }  
  60.  
  61.  
  62.  
  63.  
  64.    /**  
  65.     * Comprobar si esta repetido un objeto a partir de un valor de un atributo  
  66.     * @param attr  
  67.     * @param value  
  68.     * @return  
  69.     */  
  70.    public boolean checkRepeated(String attr, String value){  
  71.        Object obj = new Object();  
  72.        // obtener la sesion actual  
  73.        Session session = getSession();  
  74.        try {  
  75.            // comenzar la transaccion  
  76.            session.beginTransaction();  
  77.            // cargar objeto por clave  
  78.            obj = session.createCriteria(myClass.getClass()).add(Restrictions.eq(attr, value)).uniqueResult();  
  79.            // confirmar transaccion  
  80.            session.getTransaction().commit();  
  81.        } catch (Exception e) {  
  82.            System.out.println("Error en checkRepeated: " + e);  
  83.            // deshacer transaccion  
  84.            this.rollback();  
  85.        }  
  86.        return obj != null ? true : false;  
  87.    }  
  88.  
  89.    public List getListadoPiezasDeCategorias(Integer cat_id){  
  90.        
  91.        Session session = getSession();
  92.        List result = new ArrayList();  
  93.  
  94.        try {  
  95.            session.beginTransaction();  
  96.           Query query = session.createSQLQuery("select * from Producto where categoria_id=:cat_id");
  97.           query.setParameter("cat_id", cat_id);
  98.           result = query.list();
  99.  
  100.            session.getTransaction().commit();  
  101.        } catch (Exception e) {  
  102.            System.out.println("Error en getElementById: " + e);  
  103.            this.rollback();  
  104.        }  
  105.        return result;
  106.    }  
  107.    
  108.    /**  
  109.     * Obtener la sesion de hibernate para el acceso a la base de datos  
  110.     * @return  
  111.     */  
  112.    protected Session getSession(){  
  113.        Session session = null;  
  114.        try {  
  115.            session = HibernateUtil.getSessionFactory().getCurrentSession();  
  116.            if(!session.isOpen()){  
  117.                session = HibernateUtil.getSessionFactory().openSession();  
  118.            }  
  119.        } catch(Exception e){  
  120.            session = HibernateUtil.getSessionFactory().openSession();  
  121.        }  
  122.        return session;  
  123.    }  
  124.  
  125.    /**  
  126.     * Obtener el nombre de la tabla al que hace referencia  
  127.     * @return  
  128.     */  
  129.    public String getTableName(){  
  130.        return TABLE;  
  131.    }  
  132.  
  133.    /**  
  134.     * Hacer rollback y que no se termine la aplicacion tras un fallo  
  135.     */  
  136.    public void rollback(){  
  137.        Session session = getSession();  
  138.        try {  
  139.            // deshacer transaccion  
  140.            session.getTransaction().rollback();  
  141.        } catch (Exception e) {  
  142.            System.out.println("Error en rollback: " + e);  
  143.        }  
  144.    }  
  145. }