【问题标题】:My Hibernate CRUD is not saving data in the table, but its showing the table empty我的 Hibernate CRUD 没有在表中保存数据,但它显示表为空
【发布时间】:2018-12-13 07:03:02
【问题描述】:

我的程序假设从用户那里获取不同的信息来保存表格中的人,但它不保存表格中的信息,当我要求打印它时,它只是将表格打印为空。当我查看表上的数据库和查看数据时,它也没有将它们保存在那里。

这里是输入信息的HTML。

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
  xmlns:h="http://xmlns.jcp.org/jsf/html"
  xmlns:p="http://primefaces.org/ui">
<body>
    <ui:composition template="./plantilla/plantilla.xhtml">
        <ui:define name="head">
        </ui:define>
        <ui:define name="content">
            <h4>Ingresar Información</h4>
            <hr/>
            <h:form id="formulario">
                <div class="form-horizontal">
                    <div class="form-group">
                        <h:outputLabel value="Identificación" for="id" class="control-label col-sm-3"/>
                        <div class="col-sm-3">
                            <h:inputText id="id" required="true" class="form-control"
                                         requiredMessage="Campo requerido"
                                         value="#{ingresar.identificacion}">
                            </h:inputText>
                            <h:message for="id" class="text-danger"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <h:outputLabel value="Nombre" for="nombre" class="control-label col-sm-3"/>
                        <div class="col-sm-3">
                            <h:inputText id="nombre" required="true" class="form-control"
                                         requiredMessage="Campo requerido"
                                         value="#{ingresar.nombre}">
                            </h:inputText>
                            <h:message for="nombre" class="text-danger"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <h:outputLabel value="Apellido 1" for="apellido1" class="control-label col-sm-3"/>
                        <div class="col-sm-3">
                            <h:inputText id="apellido1" required="true" class="form-control"
                                         requiredMessage="Campo requerido"
                                         value="#{ingresar.apellido1}">
                            </h:inputText>
                            <h:message for="apellido1" class="text-danger"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <h:outputLabel value="Apellido 2" for="apellido2" class="control-label col-sm-3"/>
                        <div class="col-sm-3">
                            <h:inputText id="apellido2" required="true" class="form-control"
                                         requiredMessage="Campo requerido"
                                         value="#{ingresar.apellido2}">
                            </h:inputText>
                            <h:message for="apellido2" class="text-danger"/>
                        </div>
                    </div>
                    <div style="text-align: center;">
                        <h:commandButton value="Guardar" action="#{ingresar.guardarInformacion}"/>
                    </div>                        
                </div>
            </h:form>
        </ui:define>
    </ui:composition>
</body>

这是显示数据表的 HTML。

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
  xmlns:p="http://primefaces.org/ui"
  xmlns:h="http://xmlns.jcp.org/jsf/html">

<body>
    <ui:composition template="./plantilla/plantilla.xhtml">
        <ui:define name="content">
            <p:dataTable var="persona" value="#{verestudiante.personas}" rows="5" paginator="true">
                <p:column headerText="Identificacion">
                    <h:outputText value="#{personas.identificacion}"/>
                </p:column>
                <p:column headerText="Nombre">
                    <h:outputText value="#{personas.nombre}"/>
                </p:column>
                <p:column headerText="Primer Apellido">
                    <h:outputText value="#{personas.apellido1}"/>
                </p:column>
                <p:column headerText="Segundo Apellido">
                    <h:outputText value="#{personas.apellido2}"/>
                </p:column>
            </p:dataTable>
        </ui:define>

    </ui:composition>

</body>

这是 POJO,其中包含来自我们正在输入到数据库的人员的所有变量。

public class Persona {
private int idPersona;
private String nombre;
private String apellido1;
private String apellido2;
private String identificacion;


public static Persona getPersona(Persona personaParametro){
    Persona persona = new Persona();
    persona.idPersona = personaParametro.idPersona;
    persona.nombre = personaParametro.nombre;
    persona.apellido1 = personaParametro.apellido1;
    persona.apellido2 = personaParametro.apellido2;
    persona.identificacion = personaParametro.identificacion;
    return persona;
}

public int getIdPersona() {
    return idPersona;
}

public void setIdPersona(int idPersona) {
    this.idPersona = idPersona;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getApellido1() {
    return apellido1;
}

public void setApellido1(String apellido1) {
    this.apellido1 = apellido1;
}

public String getApellido2() {
    return apellido2;
}

public void setApellido2(String apellido2) {
    this.apellido2 = apellido2;
}

public String getIdentificacion() {
    return identificacion;
}

public void setIdentificacion(String identificacion) {
    this.identificacion = identificacion;
}

}

这是我们在 CRUD 中使用的 HibernateUtil。

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
    try {
        // Create the SessionFactory from standard (hibernate.cfg.xml) 
        // config file.
        //sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        // Log the exception. 
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

我们用来在 HTML dataTable 和 Database 中创建要调用的人员列表的 managedBean(requestedScope)。

public class verestudiante{
private List<Estudiante> personas = new ArrayList<Estudiante>();

public List<Estudiante> getPersonas() {
    return personas;
}

public verestudiante() {
}

@PostConstruct
public void init(){
    EstudianteGestion personaGestion = new EstudianteGestion ();
    personas = personaGestion.readPersonas();
}

}

这是我们用来在第一个 HTML 代码中插入信息的 managedBean(requestedScope)。

/**
 * Creates a new instance of ingresar
 */
public ingresar() {
}

public String guardarInformacion(){  
    PersonaGestion personaGestion = new PersonaGestion();
    Persona persona = Persona.getPersona(this);
    personaGestion.createPersona(persona);
    return "verestudiante";
}

}

最后,这是 CRUD。

public class PersonaGestion {

public void createPersona(Persona persona){
    Session session = null;
    try{
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        persona.setIdPersona((ultimoId() + 1));
        session.save(persona);
        session.getTransaction().commit();
    }
    catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    finally{
        session.close();
    }        
}

public int ultimoId(){
    Session session = null;
    try{
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        Persona ultimo = (Persona) session.createCriteria(Persona.class)
                .addOrder(Order.desc("idPersona")).setMaxResults(1).uniqueResult();
        session.getTransaction().commit();
        return ultimo.getIdPersona();
    }
    catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    finally{
        session.close();
    } 
    return -1;
}

public List<Persona> readPersonas(){
    Session session = null;
    try{
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        //Leer la informacion que esta en BD
        Query query = session.createQuery("from Tabla");
        List<Persona> lista = query.list();
        session.getTransaction().commit();
        return lista;
    }
    catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    finally{
        session.close();
    } 
    return null;
}

public Persona readPersona(String identificacion){
    Session session = null;
    try{
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        //leer una sola persona por identificacion
        Query query = session.createQuery("from Persona where identificacion = :identificacionParametro");
        query.setParameter("identificacionParametro", identificacion);
        List<Persona> lista = query.list();
        if(lista.size() > 0)
            return lista.get(0);
        session.getTransaction().commit();
    }
    catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    finally{
        session.close();
    } 
    return null;
}

public void updatePersona(Persona persona){
    Session session = null;
    try{
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        session.update(persona);
        session.getTransaction().commit();
    }
    catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    finally{
        session.close();
    } 
}

public void deletePersona(Persona persona){
    Session session = null;
    try{
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        session.delete(persona);
        session.getTransaction().commit();
    }
    catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    finally{
        session.close();
    } 
}

}

【问题讨论】:

  • 您是否尝试过调试并查看您的 html 在保存之前是否在 DTO 中正确设置了值?
  • 我刚刚调试,似乎一切正常,但我不太确定它是否在 DTO 中正确设置了值,我应该在哪里正确知道断点?
  • 你的函数ultimoId(),它有什么作用?返回数据库表中的最大ID?所以你可以在添加ID的同时添加+1?为什么此列不是自动递增的 ID。您可以尝试向 createPersona(Persona persona) 方法添加断点,并检查对象角色以查看值是否存在。我也看不到您将 DTO/POJO 映射到休眠的位置。
  • 函数ultimoId()是用来统计列表中的人数,也是DB上Table的主键,所以它为每个人和什么时候做ID你输入一个新的,它会在最后一个输入的人的数字上加 1。如果我没记错的话,Hibernate 会映射到 Persona
  • 它是否抛出任何异常?数据库中的表命名正确吗?

标签: java html database hibernate crud


【解决方案1】:

再把你的代码读清楚一遍后,错误就在一行中。

return ultimo.getIdPersona();

第一次运行时表中没有数据,所以上面的行会抛出 NullPointerException。在此异常之后,您捕获它并返回 -1,如代码中所示:

catch(Exception e){
    System.out.println("Error: " + e.getMessage());
}
finally{
    session.close();
} 
return -1;

当您返回 -1 时,personaId 变为 0,在该行中

persona.setIdPersona((ultimoId() + 1));

这个 0 导致保存数据时出错。解决此问题的一个好方法是更改​​主键的结构,它应该在数据库中定义自动递增,并且在映射中您应该将生成器设置为 identity 而不是 assigned

<generator class="identity"></generator>

或者,如果您只想正确运行代码,您应该在 ultimo 函数中执行以下操作。

session.beginTransaction();
Persona ultimo = (Persona) session.createCriteria(Persona.class)
                .addOrder(Order.desc("idPersona")).setMaxResults(1).uniqueResult();
session.getTransaction().commit();
return ultimo !=null ? ultimo.getIdPersona() : 1;

您将返回 1,第一个对象将正确存储在您的数据库中。以后你就再也不会遇到这个问题了。

希望对你有帮助。

【讨论】:

  • 如果你也能支持我的回答,我会很高兴。谢谢@LuisSequeira
猜你喜欢
  • 2022-11-19
  • 1970-01-01
  • 2014-04-21
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
相关资源
最近更新 更多