Inserting data using JPA

Asked

Viewed 453 times

0

I need help saving the data of an application using JPA. I followed a tutorial that only helped in the implementation of login but did not show how to save the data. In this case, I am trying to register a user. When I click save it shows an error message that I believe to be for lack of some 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;
    }

}

User 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;
        }
    }

}

Class Usuariomb

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 the 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>

2 answers

2


Let’s go for the friend. See that the action of the save or insert button in the case calls a method of Dao and not Bean. The jsf doesn’t know your Dao so you can’t reference it unless it has Bean’s annotation, which is not the case. What I advise you to do is to create a method insert into your bean and then call the insert method from the dao within it. Example:

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

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

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

and give a name to your example managedBean:

ManagedBean(name = "UsuarioMB")
  • Your solution solved this problem. However appeared another that should questioned in another question. Anyway thank you.

  • @Eduardokrakhecke you saw my answer?

  • yes. that question I managed to resolve.

0

Target Unreachable, identifier 'UsuarioMB' resolved to null

In xhtml, more specifically in EL, you should reference your Managedbean with lower case letter.

You’re doing it like this:

#{UsuarioMB.usuario.usuario}

It must be done like this:

#{usuarioMB.usuario.usuario}

Managedbean is being referenced several times with uppercase letter.

Change all occurrences to lower case.

  • If the user gave a name to the bean, and this was lowercase so it can be referenced with lowercase letter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.