Insert data into table with jsf,Hibernate jpa

Asked

Viewed 659 times

0

I’m having problems, in the project I’m developing in jsf using jpa and Hibernate. I am not able to register the customer data in my database as I can relate the registration ?

Code

EntityManagerFactory factory = Persistence.createEntityManagerFactory("WebApplication3PU");

EntityManager manager = factory.createEntityManager();
ClienteWeb cli= new ClienteWeb(); 
public ClienteWeb cadastrarCliente(){
           manager.getTransaction().begin();    
   manager.persist(cli);
    manager.getTransaction().commit();  
manager.close();

return cli;
    }

Customer registration

public ClienteWeb cadastrarCliente(){

manager.getTransaction().begin();    
   manager.persist(cli);
    manager.getTransaction().commit();  
manager.close();

return cli;
    }

Method with objects returned from the jsf form.

public Cliente montaCliente(){
    Cliente cli= new Cliente();
    cli.setNome(cli.getNome());
    cli.setEmail(cli.getEmail());
    cli.setSexo(cli.getSexo());
    cli.setEstado(cli.getEstado());
    cli.setSenha(cli.getSenha());
    cli.setData(cli.getData());
    cli.setCelular(cli.getCelular());
    cli.setCpf(cli.getCpf());
    cli.setCidade(cli.getCidade());
    cli.setCep(cli.getCep());
    cli.setConfirmar(cli.getConfirmar());
    cli.setRua(cli.getRua());
    cli.setNumero(cli.getNumero());
    cli.setBairro(cli.getBairro());
    cli.setUf(cli.getUf());
    cli.setLogin(cli.getLogin());

    return cli;
}

My doubt is how I will put the values of the objects typed by the user that I pick up with my class of magnedBean client and put in the method cadastrarCliente, being that in it I persist the database of my class of entiade Clienteweb ?

My class of entity

package Entity;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

 @Entity
 @Table(name = "ClienteWeb")
 @XmlRootElement

 @Entity
 @Table(name = "ClienteWeb")
  @XmlRootElement
  @NamedQueries({
   @NamedQuery(name = "ClienteWeb.findAll", query = "SELECT c FROM 
  ClienteWeb 
   c"),
   @NamedQuery(name = "ClienteWeb.findByCodigo", query = "SELECT c FROM 
   ClienteWeb c WHERE c.codigo = :codigo"),
   @NamedQuery(name = "ClienteWeb.findByEmail", query = "SELECT c FROM 
   ClienteWeb c WHERE c.email = :email"),
   @NamedQuery(name = "ClienteWeb.findByNome", query = "SELECT c FROM 
   ClienteWeb c WHERE c.nome = :nome"),
   @NamedQuery(name = "ClienteWeb.findBySexo", query = "SELECT c FROM C 
   ClienteWeb c WHERE c.sexo = :sexo"),
   @NamedQuery(name = "ClienteWeb.findByEstado", query = "SELECT c FROM 
   ClienteWeb c WHERE c.estado = :estado"),
   @NamedQuery(name = "ClienteWeb.findBySenha", query = "SELECT c FROM 
  ClienteWeb c WHERE c.senha = :senha"),
  @NamedQuery(name = "ClienteWeb.findByData", query = "SELECT c FROM 
   ClienteWeb c WHERE c.data = :data"),
   @NamedQuery(name = "ClienteWeb.findByCelular", query = "SELECT c FROM 
   ClienteWeb c WHERE c.celular = :celular"),
   @NamedQuery(name = "ClienteWeb.findByCpf", query = "SELECT c FROM 
   ClienteWeb 
   c WHERE c.cpf = :cpf"),
    @NamedQuery(name = "ClienteWeb.findByCidade", query = "SELECT c FROM 
   ClienteWeb c WHERE c.cidade = :cidade"),
  @NamedQuery(name = "ClienteWeb.findByCep", query = "SELECT c FROM 
  ClienteWeb 
 c WHERE c.cep = :cep"),
  @NamedQuery(name = "ClienteWeb.findByConfirmar", query = "SELECT c FROM 
  ClienteWeb c WHERE c.confirmar = :confirmar"),
  @NamedQuery(name = "ClienteWeb.findByRua", query = "SELECT c FROM 
ClienteWeb c WHERE c.rua = :rua"),
@NamedQuery(name = "ClienteWeb.findByNumero", query = "SELECT c FROM 
 ClienteWeb c WHERE c.numero = :numero"),
@NamedQuery(name = "ClienteWeb.findByBairro", query = "SELECT c FROM 
 ClienteWeb c WHERE c.bairro = :bairro"),
@NamedQuery(name = "ClienteWeb.findByUf", query = "SELECT c FROM ClienteWeb 
c WHERE c.uf = :uf"),
@NamedQuery(name = "ClienteWeb.findByLogin", query = "SELECT c FROM 
 ClienteWeb c WHERE c.login = :login")})
public class ClienteWeb implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "codigo")
private Integer codigo;
@Column(name = "email")
private String email;
@Column(name = "nome")
private String nome;
@Column(name = "sexo")
private String sexo;
@Column(name = "estado")
private String estado;
@Column(name = "senha")
private String senha;
@Column(name = "data")
private String data;
@Column(name = "celular")
private String celular;
@Column(name = "cpf")
private String cpf;
@Column(name = "cidade")
private String cidade;
@Column(name = "cep")
private String cep;
@Column(name = "confirmar")
private String confirmar;
@Column(name = "rua")
private String rua;
@Column(name = "numero")
private Integer numero;
@Column(name = "bairro")
private String bairro;
@Column(name = "uf")
private String uf;
@Column(name = "login")
private String login;
 @Column(name = "telefone")
private String telefone;

public ClienteWeb() {
}

public ClienteWeb(Integer codigo) {
    this.codigo = codigo;
}

public Integer getCodigo() {
    return codigo;
}

public void setCodigo(Integer codigo) {
    this.codigo = codigo;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getSexo() {
    return sexo;
}

public void setSexo(String sexo) {
    this.sexo = sexo;
}

public String getEstado() {
    return estado;
}

public void setEstado(String estado) {
    this.estado = estado;
}

public String getSenha() {
    return senha;
}

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

public String getData() {
    return data;
}

public void setData(String data) {
    this.data = data;
}

public String getCelular() {
    return celular;
}

public void setCelular(String celular) {
    this.celular = celular;
}

public String getCpf() {
    return cpf;
}

public void setCpf(String cpf) {
    this.cpf = cpf;
}

public String getCidade() {
    return cidade;
}

public void setCidade(String cidade) {
    this.cidade = cidade;
}

public String getCep() {
    return cep;
}

public void setCep(String cep) {
    this.cep = cep;
}

public String getConfirmar() {
    return confirmar;
}

public void setConfirmar(String confirmar) {
    this.confirmar = confirmar;
}

public String getRua() {
    return rua;
}

public void setRua(String rua) {
    this.rua = rua;
}

public Integer getNumero() {
    return numero;
}

public void setNumero(Integer numero) {
    this.numero = numero;
}

public String getBairro() {
    return bairro;
}

public void setBairro(String bairro) {
    this.bairro = bairro;
}

public String getUf() {
    return uf;
}

public void setUf(String uf) {
    this.uf = uf;
}

public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

public String getTelefone() {
    return telefone;
}

public void setTelefone(String telefone) {
    this.telefone = telefone;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (codigo != null ? codigo.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof ClienteWeb)) {
        return false;
    }
    ClienteWeb other = (ClienteWeb) object;
    if ((this.codigo == null && other.codigo != null) || (this.codigo != null && !this.codigo.equals(other.codigo))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "Entity.ClienteWeb[ codigo=" + codigo + " ]";
}



}

My bean that makes contact with form jsf

@ManagedBean(name="cliente")
@SessionScoped
public class Cliente {


    private final  ClienteDAO dao= new ClienteDAO();

       public  String CadastroCliente(){

        dao.cadastrarCliente();

        RequestContext.getCurrentInstance().update("grow1");
        FacesContext context=FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"","Cadastro Realizado com Sucesso"));
      return "Contato.xhtml?faces-redirect=true";

    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSexo() {
        return sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public String getSenha() {
        return senha;
    }

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

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getCelular() {
        return celular;
    }

    public void setCelular(String celular) {
        this.celular = celular;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public String getConfirmar() {
        return confirmar;
    }

    public void setConfirmar(String confirmar) {
        this.confirmar = confirmar;
    }

    public String getRua() {
        return rua;
    }

    public void setRua(String rua) {
        this.rua = rua;
    }

    public int getNumero() {
        return numero;
    }

    public void setNumero(int numero) {
        this.numero = numero;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public String getUf() {
        return uf;
    }

    public void setUf(String uf) {
        this.uf = uf;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

}
  • Sorry, I couldn’t quite understand, I’m trying to come up with an answer here. Help me, your class ClienteWeb is responsible for receiving the form data filled by the user? And you are not able to pass the class data ClienteWeb for the class Cliente who is saved on the bench?

  • Brother, you are instantiating Ciente cli = new Cliente() and is setting the values of cli, that you just instantiated into cli?

  • Your goal would not be in montaCliente(), set the values you take from the cadster form?

  • ex: cli.setCampo(campo);

  • send the form also that is better to help

  • so Henrique estou usando jsf , min ha dúvida é é como vou pegar os dados do jsf e persisti ele no banco de dados, sendo que no pesist tenho que colocar meu metodo de entidade Entity ?

  • I added the magnedBean and entity classes for you to visualize better

  • Man, the method montaCliente() should not exist. It makes no sense. In the answer I posted explain with the data are transferred from the form to the Managed bean. You got that part?

Show 3 more comments

1 answer

1

Since you didn’t post your view code, I took the liberty of creating some code snippets:


cadastraCliente.xhtml

<form>
    <p:inputText value="#{clienteMB.cliente.nome}" />
    <p:inputText value="#{clienteMB.cliente.idade}" />
    <p:inputText value="#{clienteMB.cliente.endereco}" />
    <p:commandButton actionListener="#{clienteMB.cadastraCliente}" />
</form>

Clientemb

@ManagedBean
public class ClienteMB {

    private Cliente cliente;
    private ClienteDAO dao;

    public ClienteMB() {
        this.cliente = new Cliente();
        this.dao = new ClienteDAO();
    }

    public void cadastraCliente() {
        dao.cadastraCliente(this.cliente);
    }

    public Cliente getCliente() {
        return this.cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }
}

Clientele

public class ClienteDAO() {

    EntityManagerFactory factory;
    EntityManager manager;

    public ClienteDAO() {
        this.factory = Persistence.createEntityManagerFactory("WebApplication3PU");
        this.manager = factory.createEntityManager();
    }

    public void cadastraCliente(Cliente cliente) {
        manager.getTransaction().begin();    
        manager.persist(cli);
        manager.getTransaction().commit();  
        manager.close();
    }
}

Explanation

In order to be able to transmit the data from the page to the bank, you must first pass the data from the view (xhtml) to the controller (Managedbean).

This is done by the attribute cliente class ClienteMB.

JSF can populate this attribute with the values filled when we inform on inputText the property value="#{clienteMB.cliente.nome}", for example. This way the value entered in this field will be "set" in the property nome of cliente of ClienteMB.

After that it is necessary to prepare the class ClienteDAO for her to receive a Cliente to persist (save to bank).

This is done through the method public void cadastraCliente(Cliente cliente). Note that this method receives a parameter called cliente of the kind Cliente.

In the ClienteMBthe attribute cliente is populated by input values. There we call the method the registered method passing, precisely, the attribute cliente as a parameter, thus: cadastraCliente(cliente).

Finally, the registration is performed when the user clicks on the button <p:commandButton>, who calls the method cadastraCliente() of ClienteMB.

This way it is possible to persist in the database the data from the page.


Points of Attention

  1. It is essential that the attribute cliente of ClienteMB have your methods getter and setter. It is through these methods that JSF communicates to view with the controller

  2. There are several ways to pass values of the view to the controller. That was one example

  3. The DAO is without any exception treats. Consider strongly, use try catch finally or try-with-resources, if using Java 7 or higher.

  • thanks for replying Igor, so I have to create the gets and sets of the customer so example clienteMB.cliente.name

  • The get and set are the way I wrote it. This is how the view inserts the data into Managedbean

  • then the get and set will be in the customer class ?

  • Yes. That’s right

  • 1

    man I’ll do develop the fixes and I’ll show you the code if I did this right and if the application ran, thanks for the help

  • then Igor I answered my question to be able to attach the image and you see how it became my xhtml page, the components first faces will disappear after I put in the view the magnedBean

Show 1 more comment

Browser other questions tagged

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