Data is not saved in the database

Asked

Viewed 110 times

3

I’m using Java, JPA, Primefaces, Wildfly and Mysql, not much to do, but it’s good to inform.

I fill in all the fields, all right the check is performed. When I click save the success message is displayed but nothing is saved in the bank, someone can help me identify where the error is?

I have my xhtml page:

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

    <ui:define name="conteudoForm">

        <h1>Cadastro de solicitação</h1>
        <p:spacer height="20" />
        <h:panelGrid columns="1">
            <h:panelGrid columns="1">
                <h:panelGrid columns="2">
                    <p:outputLabel value="Solicitante:"/>
                    <p:inputText id="inputSolicitante"
                        value="#{cadastroMB.cadastro.solicitante}" />
                    <p:outputLabel value="Setor:" />
                    <p:inputText id="inputSetor" value="#{cadastroMB.cadastro.setor}" />
                    <p:outputLabel value="Título da Solicitação" />
                    <p:inputText id="inputTitulo" value="#{cadastroMB.cadastro.titulo}" />
                    <p:outputLabel for="button" value="Data:" />
                    <p:calendar id="button" value="#{cadastroMB.cadastro.data}"
                        showOn="button" locale="pt_BR" pattern="dd/MM/yyyy" />
                </h:panelGrid>
                <h:panelGrid columns="2" style="margin-bottom:10px">
                    <p:outputLabel for="console" value="Prioridade:" />
                    <p:selectOneMenu id="console" value="1" style="width:130px">
                        <f:selectItem itemLabel="Selecione..." itemValue="Selecione" />
                        <f:selectItem itemLabel="Alta" itemValue="Alta" />
                        <f:selectItem itemLabel="Média" itemValue="Média" />
                        <f:selectItem itemLabel="Baixa" itemValue="baixa" />
                    </p:selectOneMenu>
                </h:panelGrid>
                <h:panelGrid>
                    <h3>Descrição da Solicitação</h3>
                    <p:editor id="editor" widgetVar="editorWidget" width="800"
                        update="@form" />
                    <h:panelGrid columns="3" style="margin-top: 10px">
                        <h:panelGroup>
                            <p:commandButton value="Enviar" action="#{cadastroMB.salvar()}"
                                update="@form">
                            </p:commandButton>
                        </h:panelGroup>
                        <p:commandButton value="Limpar" type="button"
                            onclick="PF('editorWidget').clear();" />
                    </h:panelGrid>
                </h:panelGrid>
            </h:panelGrid>
        </h:panelGrid>
    </ui:define>

</ui:composition>

This is my DAO:

package br.com.sicoob.DAO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.sicoob.Service.CadastroService;
import br.com.sicoob.entidades.Cadastro;

@Stateless
public class CadastroDAO implements Serializable, CadastroService {

    private static final long serialVersionUID = 1L;

    @PersistenceContext
    private EntityManager em;

    public void salvar(Cadastro c) {
        if (c.getId() == null) {
            em.persist(c);
        } else {
            em.merge(c);
        }
    }

    public void remover(Cadastro c) {
        c = em.merge(c);
        em.remove(c);
    }

    @SuppressWarnings("unchecked")
    public List<Cadastro> listarTodos() {
        List<Cadastro> cadastro = new ArrayList<Cadastro>();
        Query q = em.createQuery("select obj from Cadastro obj");
        cadastro = q.getResultList();
        return cadastro;
    }

    public Cadastro buscarPorId(Long id) {
        return em.find(Cadastro.class, id);
    }

    public Cadastro carregarEntidade(Cadastro c) {
        return em.merge(c);
    }

    @Override
    public void salvarUsuario(Cadastro cadastro) {
        // TODO Auto-generated method stub

    }

    @Override
    public void salvarCadastro(Cadastro cadastro) {
        // TODO Auto-generated method stub

    }
}

My entity:

package br.com.sicoob.entidades;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;

/**
 * The persistent class for the cadastro database table.
 * 
 */
@Entity
@Table(name="cadastro")
@NamedQuery(name="Cadastro.findAll", query="SELECT c FROM Cadastro c")
public class Cadastro implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    @Temporal(TemporalType.DATE)
    private Date data;

    private String descricao;

    private String prioridade;

    private String setor;

    private String solicitante;

    private String titulo;

    // getters e setters

}

My MB:

package br.com.sicoob.ManagedBeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import br.com.sicoob.Service.CadastroService;
import br.com.sicoob.entidades.Cadastro;

@ManagedBean(name = "cadastroMB")
@ViewScoped
public class CadastroMB implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private CadastroService cadastroService;

    private Cadastro cadastro = new Cadastro();
    private List<Cadastro> listaCadastro = new ArrayList<Cadastro>();
    private boolean edicao = false;

    @PostConstruct
    public void init() {
        listaCadastro = cadastroService.listarTodos();
    }

    /**
     * Método responsavel por adicionar cadastro
     */

    public void salvar() {

        if (validarCadastro(cadastro) == false) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Favor preencher todos os campos"));
            return;
        }
        cadastroService.salvarCadastro(cadastro);
        listaCadastro = cadastroService.listarTodos();

        cadastro = new Cadastro();
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "", "cadastro adicionado com sucesso"));
    }

    private boolean validarCadastro(Cadastro cadastro) {
        if (cadastro.getSolicitante() == null || "".equals(cadastro.getSolicitante())) {
            return false;
        }
        if (cadastro.getTitulo() == null || "".equals(cadastro.getTitulo())) {
            return false;
        }
        if (cadastro.getSetor() == null || "".equals(cadastro.getSetor())) {
            return false;
        }

        if (cadastro.getTitulo() == null || "".equals(cadastro.getTitulo())) {
            return false;
        }
        if (cadastro.getData() == null || "".equals(cadastro.getData())) {
            return false;

        }

        return true;
    }

    public String redirecionar() {
        return "perfil";

    }

    /**
     * Método responsavel por adicionar cadastro
     */
    public void atualizar() {
        cadastroService.salvarCadastro(cadastro);
        cadastro = new Cadastro();
        edicao = false;
    }

    public void remover(Cadastro c) {
        cadastroService.remover(c);
        listaCadastro = cadastroService.listarTodos();
        c = new Cadastro();
    }

    public void editar(Cadastro c) {
        this.cadastro = c;
        edicao = true;
    }

    public List<Cadastro> getListaCadastro() {
        return listaCadastro;
    }

    public void setListaCadastro(List<Cadastro> listaCadastro) {
        this.listaCadastro = listaCadastro;
    }

    public Cadastro getCadastro() {
        return cadastro;
    }

    public void setCadastro(Cadastro cadastro) {
        this.cadastro = cadastro;
    }

    public boolean isEdicao() {
        return edicao;
    }

    public void setEdicao(boolean edicao) {
        this.edicao = edicao;
    }
}

and the Service:

package br.com.sicoob.Service;

import java.util.List;

import br.com.sicoob.entidades.Cadastro;

public interface CadastroService {

    public List<Cadastro> listarTodos();

    public void salvarUsuario(Cadastro cadastro);

    public void salvarCadastro(Cadastro cadastro);

    public void remover(Cadastro c);

}
  • The problem may be occurring in the mapping of the entityManager( persistence.xml ), give a look at what’s on this link: http://www.tutorialspoint.com/ejb/ejb_persistence.htm

1 answer

1

I don’t work with JPA, but because of the description you gave of the behavior and your saving method. I think a commit is missing. If your connection is set to setAutoCommit(false). You have to commit at the end of the run. a look here, explains what the commit procedure with jpa http://www.java2s.com/Code/Java/JPA/StartTransactionandCommit.htm

  • Jeterson, I performed the procedure and continues in the same way!

Browser other questions tagged

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