我的 Hibernate CRUD 没有在 table 中保存数据,但显示 table 为空

My Hibernate CRUD is not saving data in the table, but its showing the table empty

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

这里是输入信息的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 和 table 数据库中创建人员列表的 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();
    } 
}

}

再看一遍你的代码,错误就在这一行。

return ultimo.getIdPersona();

第一次 运行 时 table 中没有数据,因此上面的行会抛出 NullPointerException。在这个异常之后你捕获它并且你 return -1 如代码中给出的那样:

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

当你 return -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;

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

希望对你有帮助。