Inserting data using JPA

0

I need help saving the data of an application using JPA. I followed a tutorial that only helped in the implementation of the login but did not show how to save the data. In this case, I'm trying to register a user. When I click save it shows an error message that I believe is due to lack of any implementation:

 javax.el.PropertyNotFoundException: /cadUsuario.xhtml @22,136 value="#{UsuarioMB.usuario.usuario}": Target Unreachable, identifier 'UsuarioMB' resolved to null

User Class

 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 = "USUARIOS")
//@NamedQuery(name="query", query="SELECT c FROM Cliente c")
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private long id;

    @Column(name = "USUARIO", length = 10, nullable = false)
    private String usuario;

    @Column(name = "SENHA", length = 5, nullable = false)
    private String senha;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

}

UserID class

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import model.Usuario;

public class UsuarioDAO {

    private EntityManagerFactory factory = Persistence
            .createEntityManagerFactory("usuarios");
    private EntityManager em = factory.createEntityManager();

    public Usuario getUsuario(String usuario, String senha) {

        try {
            Usuario usu = (Usuario) em
                    .createQuery(
                            "SELECT u from Usuario u where u.usuario = :usuario and u.senha = :senha")
                    .setParameter("usuario", usuario)
                    .setParameter("senha", senha).getSingleResult();

            return usu;
        } catch (NoResultException e) {
            return null;
        }
    }

    public boolean inserirUsuario(Usuario usuario) { 

        try {         
            em.persist(usuario);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean deletarUsuario(Usuario usuario) {
        try {
            em.remove(usuario);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}

UserMB class

import daos.UsuarioDAO;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import model.Usuario;

@ManagedBean
@SessionScoped
public class UsuarioMB {

    private Usuario usuario;

    public UsuarioMB() {

    }



    public UsuarioMB(Usuario usuario) {
        this.usuario = usuario;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

}

registration page in case

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:ui="http://java.sun.com/jsf/facelets">

    <h:head>
        <title>Lavagem Godoi</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
    </h:head>
    <ui:include src="menu/menu.xhtml" />
    <h:body>
        <h:form>
            <p:growl id="msgs"/>
            <p:messages id="messages" />
            <p:fieldset legend="Cadastro de Usuário" style="margin-bottom:20px">
                <h:panelGrid columns="2" cellpadding="5">
                    <p:outputLabel for="id" value="Id"  />
                    <p:inputText id="id" value="#{UsuarioMB.usuario.id}" disabled="true" />

                    <p:outputLabel for="usuario" value="Nome do Usuário:" />
                    <p:inputText id="usuario" value="#{UsuarioMB.usuario.usuario}" required="true" requiredMessage="Insira o usuário"/>

                    <p:outputLabel for="senha" value="Senha:" />
                    <p:password id="senha" value="#{UsuarioMB.usuario.senha}" required="true" requiredMessage="Insira a senha"/>

                    <p:commandButton value="Salvar" action="#{UsuarioDAO.inserirUsuario}" > </p:commandButton>
                </h:panelGrid>
            </p:fieldset>
        </h:form>
    </h:body>

</html>
    
asked by anonymous 23.05.2017 / 16:51

2 answers

1

Let's do it for the friend. Notice that the button action save or insert in the case calls a Dao method, not the Bean method. The jsf does not know your Dao so you can not reference it unless it is with the Bean annotation which is not the case. What I advise you to do is create a method insert into your bean and then call the insert method of dao inside it. Example:

public void inserir(){
dao.inserir(usuario)
}

This error is not related to JPA, but to the value of your property that is null. Create an initial method on your ManagedBean with the @PostConstruct annotation, and start your property, for example:

@PostConstruct
public void init(){
  usuario = new Usuario();
}

and give a name for your managedBean example:

ManagedBean(name = "UsuarioMB")
    
23.05.2017 / 22:56
0
  

Target Unreachable, identifier 'UsuarioMB' resolved to null

In xhtml, more specifically in EL, you should reference your ManagedBean in lowercase.

You're doing it like this:

#{UsuarioMB.usuario.usuario}

It should be done like this:

#{usuarioMB.usuario.usuario}

The ManagedBean is being referenced several times in uppercase.

Change all occurrences to lowercase.

    
24.05.2017 / 01:10