Change JPA / JPQL record [closed]

1

I'm doing my first WEB project and I have a question about using JPA / JPQL / MERGE.

The question is:

I need to change a record of a table, I've created a dataTable that returns me a list of Open Tickets. This table is populated by my Value Object class. This was the way I was able to fetch data by joining them in other classes. (This table has 3 FK's.)

I need the user to select an item from the list and click change, open a Dialog with the filled fields, and can make the change.

But since the class that populates my table is "different" from the one I need to change then I can not complete the change. I can select and make the information appear in the dialog, but I need to change the list to fill the dataTable, so it does not have the Joins.

Usedcode(Tablescreen):

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

<ui:define name="conteudo">
    <div class="row">
        <h1>Consulta de Tickets Abertos</h1>
    </div>

    <h:form>
        <p:dataTable value="#{listaTicketAberto.listaticket}" 
                     var="ticket" 

                     rowKey="#{ticket.id}" id="tbl-tkt" 
                     selectionMode="single"
                     selection="#{ticketController.tktSelecionado}"
                     >

            <f:facet name="header">Tabela de Tickets Abertos</f:facet>

            <p:column headerText="Planta">
                #{ticket.planta}
            </p:column>

            <p:column headerText="Projeto">
                #{ticket.projeto}
            </p:column>
            <p:column headerText="Fornecedor">
                #{ticket.fornecedor}
            </p:column>

            <p:column headerText="Titulo">
                #{ticket.titulo}
            </p:column>            
            <p:column headerText="Tipo">
                #{ticket.tipo}
            </p:column>            

            <p:column headerText="Status">
                #{ticket.status}
            </p:column>            

            <p:column headerText="Usuario">
                #{ticket.usuario}
            </p:column>            
        </p:dataTable>      
        <p:commandButton process="tbl-tkt" 
                         update=":formDlg:grupo-campos"                                      
                         value="Editar" 
                         oncomplete="PF('ticketDialog').show()" 
                         action="#{ticketController.update}"/>
    </h:form>

    <h:form id="formDlg">

        <p:dialog header="Formulário" widgetVar="ticketDialog" minHeight="40" id="dlg1">

            <h:panelGroup id="grupo-campos">
                <h:panelGrid >
                    <h:outputLabel value="Numero do Ticke: #{ticketController.tktSelecionado.id}" />

                    <h:outputLabel value="Titulo #{ticketController.tktSelecionado.titulo}"/>


                    <h:outputLabel value="Solução" for="campo-solucao"/>
                    <h:inputTextarea styleClass="form-control" value="#{ticketController.tktSelecionado.solucao}"
                                     id="campo-solucao"
                                     required="true">
                    </h:inputTextarea>                

                    <h:outputLabel value="Update" for="campo-update"/>
                    <h:inputTextarea styleClass="form-control" value="#{ticketController.tktSelecionado.atualizacao}"
                                     id="campo-update"
                                     required="true">
                    </h:inputTextarea>        

                    <h:outputLabel for="status" value="Status" />
                    <h:selectOneMenu id="status" value="#{ticketController.tktSelecionado.status}"  styleClass="form-control" >
                        <f:selectItem itemLabel="---Selecione---"  />
                        <f:selectItem itemLabel="Working" itemValue="Working" />
                        <f:selectItem itemLabel="Wait On User" itemValue="Wait On User" />
                        <f:selectItem itemLabel="Resolved" itemValue="Resolved" />
                        <f:selectItem itemLabel="Wait On External" itemValue="Wait On External" />
                    </h:selectOneMenu>

                </h:panelGrid>
                <h:commandButton id="save" 
                                 styleClass="btn btn-success" 
                                 value="Salvar" 
                                 action="#{ticketController.salvarTicket}">
                    <f:ajax execute="@form" render=":form:tbl-tkt grupo-campos"/>
                </h:commandButton>
                <h:button styleClass="btn btn-warning" onclick="PF('ticketDialog').hide()" value="Fechar"/>
            </h:panelGroup>

        </p:dialog>

    </h:form>


</ui:define>

Class V.O:

package br.com.senai.vo;

import java.io.Serializable;
import java.util.Objects;



public class TicketVO implements Serializable {

private Long id;

private String planta;

private String projeto;
private String fornecedor;
private String titulo;
private String tipo;
private String status;
private String usuario;

public TicketVO(Long id, String planta, String projeto, String fornecedor, String titulo, String tipo, String status, String usuario) {
    this.id = id;
    this.planta = planta;
    this.projeto = projeto;
    this.fornecedor = fornecedor;
    this.titulo = titulo;
    this.tipo = tipo;
    this.status = status;
    this.usuario = usuario;
}

public TicketVO() {
}




public String getTipo() {
    return tipo;
}

public void setTipo(String tipo) {
    this.tipo = tipo;
}




public Long getId() {
    return id;
}

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

public String getPlanta() {
    return planta;
}

public void setPlanta(String planta) {
    this.planta = planta;
}

public String getProjeto() {
    return projeto;
}

public void setProjeto(String projeto) {
    this.projeto = projeto;
}

public String getTitulo() {
    return titulo;
}

public void setTitulo(String titulo) {
    this.titulo = titulo;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getUsuario() {
    return usuario;
}

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

public String getFornecedor() {
    return fornecedor;
}

public void setFornecedor(String fornecedor) {
    this.fornecedor = fornecedor;
}

@Override
public int hashCode() {
    int hash = 7;
    hash = 11 * hash + Objects.hashCode(this.id);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final TicketVO other = (TicketVO) obj;
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    return true;
}    
}

Class list:

package br.com.senai.controller;

import br.com.senai.model.Ticket;
import br.com.senai.repository.TicketRepository;
import br.com.senai.vo.TicketVO;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;

@ManagedBean
public class ListaTicketAberto implements Serializable {

private List<TicketVO> listaticket = new ArrayList<>();
private TicketRepository repository = new TicketRepository();

public ListaTicketAberto() {
    listaticket = repository.getListaVO();
}    

public List<TicketVO> getListaticket() {
    return listaticket;
}

public void setListaticket(List<TicketVO> listaticket) {
    this.listaticket = listaticket;
}

public TicketRepository getRepository() {
    return repository;
}

public void setRepository(TicketRepository repository) {
    this.repository = repository;
}

}

Repository:

package br.com.senai.repository;

import br.com.senai.controller.JPAListener;
import br.com.senai.model.Ticket;
import br.com.senai.vo.TicketVO;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;



public class TicketRepository {

EntityManager em = JPAListener.createEntityManager();

List<Ticket> listaTkt = new ArrayList<>();

public void addTicket(Ticket os) {
    em.getTransaction().begin();
    try {
        em.persist(os);
        em.getTransaction().commit();
    } catch (Exception e) {
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
}

public List<Ticket> getLista() {
    List<Ticket> tickets
            = em.createQuery("select t from Ticket t ")
                    .getResultList();
    return tickets;
}

public Ticket getTicket(Long id) {
    Ticket ticket = em.find(Ticket.class, id);
    return ticket;
}

public void alterar(Ticket ticket) {
    Ticket ticketUpdate = getTicket(ticket.getId());
    em.getTransaction().begin();
    try {
        em.merge(ticketUpdate);
        em.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        em.getTransaction().rollback();
    }
}

public List<TicketVO> getListaVO() {
    List<TicketVO> tickets;
    tickets = em.createQuery("select new br.com.senai.vo.TicketVO(t.id, p.codigo, pr.nome ,f.nome, t.titulo, t.tipo, t.status, t.usuario) "
            + "from Ticket t "
            + "join t.planta p "
            + "join t.projeto pr "
            + "join t.fornecedor f "
            + "where t.status in ('Working','Wait On User','Wait On External')")
            .getResultList();
    return tickets;
}

}

Controller:

package br.com.senai.controller;

import br.com.senai.model.Planta;
import br.com.senai.model.Fornecedor;
import br.com.senai.model.Projeto;
import br.com.senai.model.Ticket;
import br.com.senai.model.Usuario;
import br.com.senai.repository.PlantaRepository;
import br.com.senai.repository.FornecedorRepository;
import br.com.senai.repository.ProjetoRepository;
import br.com.senai.repository.TicketRepository;
import br.com.senai.repository.UsuarioRepository;
import br.com.senai.vo.TicketVO;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class TicketController implements Serializable {

private Ticket ticketModel = new Ticket();
private Ticket tktSelecionado = new Ticket();


private List<Planta> plantaLista = new ArrayList<>();
private List<Projeto> projetoLista = new ArrayList<>();
private List<Fornecedor> fornecedorLista = new ArrayList<>();
private List<Usuario> usuarioLista = new ArrayList<>();
private List<Ticket> ticketLista = new ArrayList<>();
private TicketRepository toRepository = new TicketRepository();
private FornecedorRepository foRepository = new FornecedorRepository();
private ProjetoRepository ProjetoRepository = new ProjetoRepository();
private PlantaRepository PlantaRepository = new PlantaRepository();
private UsuarioRepository UsuarioRepository = new UsuarioRepository();
private SpringBean spring;

public TicketController() {
    try {
        this.spring = new SpringBean();
    } catch (IOException ex) {
        Logger.getLogger(TicketController.class.getName()).log(Level.SEVERE, null, ex);
    }

    plantaLista = PlantaRepository.getPlantas();
    projetoLista = ProjetoRepository.getProjetos();
    fornecedorLista = foRepository.getLista();

}

public void salvarTicket() {

    if (this.tktSelecionado.getId() == null) {
        try {
            this.ticketModel.setUsuario(spring.getUsuario());
            this.ticketModel.setAberto(new Date());
            toRepository.addTicket(ticketModel);
            ticketModel = new Ticket();
            FacesMessage mensagem = new FacesMessage("Ticket aberto com sucesso!");
            FacesContext.getCurrentInstance().addMessage(null, mensagem);

        } catch (Exception e) {
            FacesMessage mensagem = new FacesMessage(e + "erro");
            FacesContext.getCurrentInstance().addMessage(null, mensagem);

        }
    } else {
        this.tktSelecionado.setUsuario(spring.getUsuario());
        this.tktSelecionado.setAberto(new Date());
        toRepository.alterar(tktSelecionado);
    }

}

//metodo chamado no front end pra setar o tktselecionado 
public void update() {
    this.tktSelecionado = this.ticketModel;
}

public Ticket getTktSelecionado() {
    return tktSelecionado;
}

public void setTktSelecionado(Ticket tktSelecionado) {
    this.tktSelecionado = tktSelecionado;
}

public List<Ticket> getTicketLista() {
    return ticketLista;
}

public void setTicketLista(List<Ticket> ticketLista) {
    this.ticketLista = ticketLista;
}

public List<Usuario> getUsuarioLista() {
    return usuarioLista;
}

public void setUsuarioLista(List<Usuario> usuarioLista) {
    this.usuarioLista = usuarioLista;
}

public UsuarioRepository getUsuarioRepository() {
    return UsuarioRepository;
}

public void setUsuarioRepository(UsuarioRepository UsuarioRepository) {
    this.UsuarioRepository = UsuarioRepository;
}

public Ticket getTicketModel() {
    return ticketModel;
}

public void setTicketModel(Ticket ticketModel) {
    this.ticketModel = ticketModel;
}

public List<Planta> getPlantaLista() {
    return plantaLista;
}

public void setPlantaLista(List<Planta> plantaLista) {
    this.plantaLista = plantaLista;
}

public List<Projeto> getProjetoLista() {
    return projetoLista;
}

public void setProjetoLista(List<Projeto> projetoLista) {
    this.projetoLista = projetoLista;
}

public List<Fornecedor> getFornecedorLista() {
    return fornecedorLista;
}

public void setFornecedorLista(List<Fornecedor> fornecedorLista) {
    this.fornecedorLista = fornecedorLista;
}

public TicketRepository getToRepository() {
    return toRepository;
}

public void setToRepository(TicketRepository toRepository) {
    this.toRepository = toRepository;
}

public FornecedorRepository getFoRepository() {
    return foRepository;
}

public void setFoRepository(FornecedorRepository foRepository) {
    this.foRepository = foRepository;
}

public ProjetoRepository getProjetoRepository() {
    return ProjetoRepository;
}

public void setProjetoRepository(ProjetoRepository ProjetoRepository) {
    this.ProjetoRepository = ProjetoRepository;
}

public PlantaRepository getPlantaRepository() {
    return PlantaRepository;
}

public void setPlantaRepository(PlantaRepository PlantaRepository) {
    this.PlantaRepository = PlantaRepository;
}

}

Ps: I tried to create a Converter class for each class, I already used it to fill a selectOneMenu element and it works, but I do not know how I would use it in this situation. I also do not know if my MERGE is 100% certain because until now I could not get it to work.

If anyone can give me a light there I thank.

    
asked by anonymous 14.12.2017 / 02:55

0 answers