Fórum popular combo com dados do banco de dados #526014
16/07/2015
0
Sou iniciante em java e estou desenvolvendo um projeto mas parei na parte de cadastro onde queria saber como faço para puxar os estados cadastrados no banco de dados para uma combo e ao clicar no estado, vir as cidades do estado selecionado. Meu banco de dados é em postgres, estou usando jpa + hibernate + primefaces. Tenho classes genéricas que se tirar as opções de cidade e estados relacionados no banco, funciona corretamente. Alguem pode me ajudar e tirar minha dúvida? segue todo meu projeto abaixo. Java EE com framework
minhas classes:
classe pessoa
@Entity
@Table(name = "tb_pessoa")
@SequenceGenerator(name = "pessoa_sequence", sequenceName = "seq_tb_pessoa", allocationSize = 1)
public class Pessoa {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pessoa_sequence")
@Column(name = "cod_pessoa")
private Long id;
@Column(name = "pessoa", nullable = false)
private String nome;
@Column(name="endereco", nullable=false)
private String endereco;
@ManyToOne(optional=false)
@JoinColumn(name = "id_cidade")
private Cidade cidade;
@ManyToOne(optional=false)
@JoinColumn(name = "id_estado")
private Estado uf;
@Column(name="cep", nullable=false)
private String cep;
@Column(name="n_rg", nullable=false)
private String rg;
@Column(name="orgExpedidor", nullable=false)
private String orgExpedidor;
@Column(name="cpf", nullable=false)
private String cpf;
@Column(name="estCivil", nullable=false)
private String estadoCivil;
@Column(name="telefone", nullable=false)
private String telefone;
@Column(name="dt_nasc", nullable=false)
@Temporal(TemporalType.DATE)
private Date dataNascimento;
@Column(name="email", nullable=false)
private String email;
getter e setter ocultos equals e hashcolds ocultos
---------------------------------------------------------------------
classe cidade
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "tb_cidade")
@SequenceGenerator(name = "cidade_sequence", sequenceName = "seq_tb_cidade", allocationSize = 1)
public class Cidade implements Serializable{
private static final long serialVersionUID = 7239792152876994366L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cidade_sequence")
@Column(name = "id_cidade")
private Long id_cidade;
@Column(name = "nome", nullable = false)
private String nome;
@ManyToOne(optional=false)
@JoinColumn(name = "id_estado")
private Estado estado;
get e set ocultos
--------------------------------------------------------------------------
classe estado
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.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "tb_estado")
@SequenceGenerator(name = "estado_sequence", sequenceName = "seq_tb_estado", allocationSize = 1)
public class Estado implements Serializable {
private static final long serialVersionUID = -3243642346092867036L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "estado_sequence")
@Column(name = "id_estado")
private Long id;
@Column(name = "uf", nullable = false)
private String uf;
get e set ocultos
---------------------------------------------------------------------------------------------------------------------------------
meus daos:
interface DAO
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
public interface DAO<E,ID> extends Serializable {
public void create(E entity);
public E read(ID identity);
public Collection<E> read();
public void update(E entity);
public void delete(E entity);
-------------------------------------------------------------------------
PessoaDAO
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
import com.unimedcerrado.projeto.modelo.Pessoa;
@Stateless
public class PessoaDAO extends GenericDAO<Pessoa, Long> {
private static final long serialVersionUID = 3693934000644444548L;
@PersistenceContext(unitName = "primary")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Override
protected Class<Pessoa> getEntityClass() {
return Pessoa.class;
}
@Override
public void delete(Pessoa entity) {
String hql = "Delete From Pessoa e Where e.id = :id";
this.getEntityManager().createQuery(hql)
.setParameter("id", entity.getId()).executeUpdate();
}
public boolean existePessoaComRg(Pessoa entity) {
String hql = "Select e From Pessoa Where e.rg = :rgPagam";
if (entity.getId() != null) {
hql = hql + " and e.id != :idParam";
Query query = this.getEntityManager().createQuery(hql);
query.setParameter("rgParam", entity.getRg());
if (entity.getId() != null) {
query.setParameter("idParam", entity.getId());
}
return query.getResultList().size()>0;
}
return false;
}
-----------------------------------------------------------------------------------------------
cidadeDAO
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
@Stateless
public class CidadeDAO extends GenericDAO<Cidade, Long> {
private static final long serialVersionUID = 922388200167605258L;
@PersistenceContext(unitName = "primary")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Override
protected Class<Cidade> getEntityClass() {
return Cidade.class;
}
---------------------------------------------------------------------------------
estadoDAO
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
@Stateless
public class EstadoDAO extends GenericDAO<Estado, Long> {
private static final long serialVersionUID = 6953659285095057355L;
@PersistenceContext(unitName = "primary")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Override
protected Class<Estado> getEntityClass() {
return Estado.class;
}
@Override
public void delete(Estado entity) {
String hql = "Delete From Estado e Where e.id = :id";
this.getEntityManager().createQuery(hql)
.setParameter("id", entity.getId()).executeUpdate();
}
---------------------------------------------------------------------
genericDAO
import java.util.Collection;
import javax.persistence.EntityManager;
public abstract class GenericDAO<E, ID> implements DAO<E, ID> {
private static final long serialVersionUID = 1361504652223309748L;
protected abstract EntityManager getEntityManager();
protected abstract Class<E> getEntityClass();
protected String getQueryAll() {
return String.format("Select e From %s e", this.getEntityClass()
.getSimpleName());
}
@Override
public void create(E entity) {
this.getEntityManager().persist(entity);
}
@Override
public E read(ID identity) {
return this.getEntityManager().find(this.getEntityClass(), identity);
}
@SuppressWarnings("unchecked")
@Override
public Collection<E> read() {
return this.getEntityManager().createQuery(this.getQueryAll())
.getResultList();
}
@Override
public void update(E entity) {
this.getEntityManager().merge(entity);
}
@Override
public void delete(E entity) {
this.getEntityManager();
this.getEntityManager().remove(entity);
}
}
--------------------------------------------------------------------------------------------
Classes Serviço
estadoServico
import javax.ejb.EJB;
import com.unimedcerrado.projeto.modelo.Estado;
import com.unimedcerrado.projeto.persistencia.EstadoDAO;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public class EstadoServico extends GenericServico<Estado, Long> {
private static final long serialVersionUID = 930006390851601875L;
@EJB
private EstadoDAO dao;
@Override
public void create(Estado entity) throws NegocioException {
super.create(entity);
}
@Override
public void update(Estado entity) throws NegocioException {
super.update(entity);
}
@Override
public EstadoDAO getDAO() {
return this.dao;
}
}
----------------------------------------------------------------------------------------------
GenericServico
import java.util.Collection;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public abstract class GenericServico<E, ID> implements Servico<E, ID> {
private static final long serialVersionUID = -7536525219057881564L;
@Override
public void create(E entity) throws NegocioException {
this.getDAO().create(entity);
}
@Override
public E read(ID identity) {
return this.getDAO().read(identity);
}
@Override
public Collection<E> read() {
return this.getDAO().read();
}
@Override
public void update(E entity) throws NegocioException {
this.getDAO().update(entity);
}
@Override
public void delete(E entity) throws NegocioException {
this.getDAO().delete(entity);
}
}
-----------------------------------------------------------------------------------
servico
import java.io.Serializable;
import java.util.Collection;
import com.unimedcerrado.projeto.persistencia.DAO;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public interface Servico<E,ID> extends Serializable {
public DAO<E,ID> getDAO();
public void create(E entity) throws NegocioException;
public E read(ID identity);
public Collection<E> read();
public void update(E entity) throws NegocioException;
public void delete(E entity) throws NegocioException;
}
----------------------------------------------------------------------------------------
NegocioException
public class NegocioException extends RuntimeException{
private static final long serialVersionUID = -5493360949338751713L;
public NegocioException(String msg){
super(msg);
}
}
-----------------------------------------------------------------------------------
ManagedBeans:
GenericBean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import com.unimedcerrado.projeto.servico.Servico;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public abstract class GenericBean<E, ID, S extends Servico<E, ID>> implements
Serializable{
private static final long serialVersionUID = 1908229635425203875L;
private E formulario;
protected abstract S getServico();
@PostConstruct
protected abstract void inicializar();
public void adicionarMensagem(String mensagem) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(mensagem));
}
public void salvar() {
try {
this.getServico().create(this.getFormulario());
this.adicionarMensagem("Cadastrado com Sucesso!");
this.inicializar();
} catch (NegocioException e) {
this.adicionarMensagem(e.getMessage());
}
}
public void alterar() {
try {
this.getServico().update(this.getFormulario());
this.adicionarMensagem("Alteração realizada com Sucesso!");
this.inicializar();
} catch (NegocioException e) {
this.adicionarMensagem(e.getMessage());
}
}
public void remover(E entity) {
try {
this.getServico().delete(entity);
this.adicionarMensagem("Removido com Sucesso!");
} catch (NegocioException e) {
this.adicionarMensagem(e.getMessage());
}
}
public E getFormulario() {
return formulario;
}
public List<E> getEntidades() {
return new ArrayList<E>(this.getServico().read());
}
public void setFormulario(E formulario) {
this.formulario = formulario;
}
}
------------------------------------------------------------------------------------
PessoaBean
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.unimedcerrado.projeto.modelo.Pessoa;
import com.unimedcerrado.projeto.servico.PessoaServico;
@Named
@SessionScoped
public class PessoaBean extends GenericBean<Pessoa, Long, PessoaServico> {
private static final long serialVersionUID = 95889200604449740L;
@Inject
private PessoaServico servico;
@Override
protected PessoaServico getServico() {
return this.servico;
}
@Override
protected void inicializar() {
this.setFormulario(new Pessoa());
}
}
------------------------------------------------------------------
EstadoBean
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.unimedcerrado.projeto.modelo.Estado;
import com.unimedcerrado.projeto.servico.EstadoServico;
@Named
@SessionScoped
public class EstadoBean extends GenericBean<Estado, Long, EstadoServico> {
private static final long serialVersionUID = 4968510186149193943L;
@Inject
private EstadoServico servico;
@Override
protected EstadoServico getServico() {
return this.servico;
}
@Override
protected void inicializar() {
this.setFormulario(new Estado());
}
}
------------------------------------------------------------------------------------------------
meu xhtml
CadastroPessoas.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="/WEB-INF/template/Layout.xhtml">
<f:metadata>
<f:view action="#{pessoaBean.entidades}" />
</f:metadata>
<ui:define name="titulo">Sistema de Cadastros e Lançamentos</ui:define>
<ui:define name="corpo">
<p:panel header="Cadastro de Pessoas" rendered="true">
<h:form id="frmCadastroPessoas">
<p:messages />
<h:panelGrid columns="2" cellpadding="2" rendered="true"
style="width: 60%; text-align:left">
<p:outputLabel for="nome" value="Nome:" style="width: 100px;" />
<p:inputText style="width: 293px;" id="nome" required="true"
requiredMessage="O campo Nome é obrigatório!"
value="#{pessoaBean.formulario.nome}"
onchange="this.value = this.value.toUpperCase();"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:validateLength minimum="20" maximum="100" for="nome" />
</p:inputText>
<p:outputLabel for="endereco" value="Endereço:"
style="width: 100px;" />
<p:inputText style="width: 300px;" id="endereco" required="true"
requiredMessage="O campo Endereço é obrigatório!"
value="#{pessoaBean.formulario.endereco}"
onchange="this.value = this.value.toUpperCase();"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:validateLength minimum="20" maximum="200" for="nome" />
</p:inputText>
<p:outputLabel for="estado" value="UF:" />
<p:selectOneMenu id="estado" var="estado" required="false"
value="#{estadoBean.entidades}" style="width:85px"
requiredMessage="O campo UF é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="#{estado.uf}" />
<f:selectItems value="#"/>
</p:selectOneMenu>
<p:outputLabel for="cidade" value="Cidade:" />
<p:inputText id="cidade" required="true"
requiredMessage="O campo Cidade é obrigatório!"
value="#{pessoaBean.formulario.cidade}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="cep" value="Cep:" />
<p:inputMask mask="99.999-999" id="cep" required="true"
requiredMessage="O campo Cep é obrigatório!"
value="#{pessoaBean.formulario.cidade}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="rg" value="RG:" />
<p:inputMask mask="9999999" id="rg" required="true"
requiredMessage="O campo Rg é obrigatório!"
value="#{pessoaBean.formulario.rg}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="oexp" value="Orgão Expedidor:" />
<p:selectOneMenu id="oexp" required="true"
value="#{pessoaBean.formulario.orgExpedidor}" style="width:125px"
requiredMessage="O campo Orgão Expedidor é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="" />
<f:selectItem itemLabel="CGPI/DUREX/DPF"
itemValue="CGPI/DUREX/DPF" />
<f:selectItem itemLabel="SDS" itemValue="SDS" />
<f:selectItem itemLabel="SNJ" itemValue="SNJ" />
<f:selectItem itemLabel="SECC" itemValue="SECC" />
<f:selectItem itemLabel="SEJUSP" itemValue="SEJUSP" />
<f:selectItem itemLabel="SES/EST" itemValue="SES/EST" />
<f:selectItem itemLabel="SESP" itemValue="SESP" />
<f:selectItem itemLabel="SJS" itemValue="SJS" />
<f:selectItem itemLabel="SJTC" itemValue="SJTC" />
<f:selectItem itemLabel="SJTS" itemValue="SJTS" />
<f:selectItem itemLabel="SPTC" itemValue="SPTC" />
<f:selectItem itemLabel="SSP" itemValue="SSP" />
</p:selectOneMenu>
<p:outputLabel for="uf" value="UF:" />
<p:selectOneMenu id="uf" required="false"
value="#{pessoaBean.formulario.uf}" style="width:125px"
requiredMessage="O campo UF é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="" />
<f:selectItem itemLabel="AC" itemValue="AC" />
<f:selectItem itemLabel="AL" itemValue="AL" />
<f:selectItem itemLabel="AP" itemValue="AP" />
<f:selectItem itemLabel="AM" itemValue="AM" />
<f:selectItem itemLabel="BA" itemValue="BA" />
<f:selectItem itemLabel="CE" itemValue="CE" />
<f:selectItem itemLabel="DF" itemValue="DF" />
<f:selectItem itemLabel="ES" itemValue="ES" />
<f:selectItem itemLabel="GO" itemValue="GO" />
<f:selectItem itemLabel="MA" itemValue="MA" />
<f:selectItem itemLabel="MT" itemValue="MT" />
<f:selectItem itemLabel="MS" itemValue="MS" />
<f:selectItem itemLabel="MG" itemValue="MG" />
<f:selectItem itemLabel="PA" itemValue="PA" />
<f:selectItem itemLabel="PB" itemValue="PB" />
<f:selectItem itemLabel="PR" itemValue="PR" />
<f:selectItem itemLabel="PE" itemValue="PE" />
<f:selectItem itemLabel="PI" itemValue="PI" />
<f:selectItem itemLabel="RJ" itemValue="RJ" />
<f:selectItem itemLabel="RN" itemValue="RN" />
<f:selectItem itemLabel="RS" itemValue="RS" />
<f:selectItem itemLabel="RO" itemValue="RO" />
<f:selectItem itemLabel="RR" itemValue="RR" />
<f:selectItem itemLabel="SC" itemValue="SC" />
<f:selectItem itemLabel="SP" itemValue="SP" />
<f:selectItem itemLabel="SE" itemValue="SE" />
<f:selectItem itemLabel="TO" itemValue="TO" />
</p:selectOneMenu>
<p:outputLabel for="cpf" value="Cpf:" />
<p:inputMask mask="999.999.999-99" id="cpf" required="true"
requiredMessage="O campo Cpf é obrigatório!"
value="#{pessoaBean.formulario.cpf}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="estCivil" value="Estado Civil:" />
<p:selectOneMenu id="estCivil" required="true"
value="#{pessoaBean.formulario.estadoCivil}" style="width:125px"
requiredMessage="O campo Estado Civil é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="" />
<f:selectItem itemLabel="Solteiro(a)" itemValue="Solteiro(a)" />
<f:selectItem itemLabel="Casado(a)" itemValue="Casado(a)" />
<f:selectItem itemLabel="Divorciado(a)" itemValue="Divorciado(a)" />
<f:selectItem itemLabel="Viúvo(a)" itemValue="Viúvo(a)" />
<f:selectItem itemLabel="Companheiro(a)" itemValue="Companheiro(a)" />
</p:selectOneMenu>
<p:outputLabel for="telefone" value="Telefone:" />
<p:inputMask mask="(99) 9999-9999" id="telefone" required="true"
requiredMessage="O campo Telefone é obrigatório!"
value="#{pessoaBean.formulario.telefone}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="dn" value="Data Nascimento:" />
<p:calendar id="dn" size="12" locale="pt_BR" navigator="true"
pattern="dd/MM/yyyy"
value="#{pessoaBean.formulario.dataNascimento}" />
<p:outputLabel for="email" value="E-mail:" />
<p:inputText id="email" value="#{pessoaBean.formulario.email}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
</h:panelGrid>
<p:commandButton
rendered="#{manutencaoPessoaBean.formulario.id == null}"
update="@form" value="Cadastrar" icon="ui-icon-disk"
actionListener="#{pessoaBean.salvar()}" />
</h:form>
</p:panel>
</ui:define>
</ui:composition>
</html>
minhas classes:
classe pessoa
@Entity
@Table(name = "tb_pessoa")
@SequenceGenerator(name = "pessoa_sequence", sequenceName = "seq_tb_pessoa", allocationSize = 1)
public class Pessoa {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pessoa_sequence")
@Column(name = "cod_pessoa")
private Long id;
@Column(name = "pessoa", nullable = false)
private String nome;
@Column(name="endereco", nullable=false)
private String endereco;
@ManyToOne(optional=false)
@JoinColumn(name = "id_cidade")
private Cidade cidade;
@ManyToOne(optional=false)
@JoinColumn(name = "id_estado")
private Estado uf;
@Column(name="cep", nullable=false)
private String cep;
@Column(name="n_rg", nullable=false)
private String rg;
@Column(name="orgExpedidor", nullable=false)
private String orgExpedidor;
@Column(name="cpf", nullable=false)
private String cpf;
@Column(name="estCivil", nullable=false)
private String estadoCivil;
@Column(name="telefone", nullable=false)
private String telefone;
@Column(name="dt_nasc", nullable=false)
@Temporal(TemporalType.DATE)
private Date dataNascimento;
@Column(name="email", nullable=false)
private String email;
getter e setter ocultos equals e hashcolds ocultos
---------------------------------------------------------------------
classe cidade
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "tb_cidade")
@SequenceGenerator(name = "cidade_sequence", sequenceName = "seq_tb_cidade", allocationSize = 1)
public class Cidade implements Serializable{
private static final long serialVersionUID = 7239792152876994366L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cidade_sequence")
@Column(name = "id_cidade")
private Long id_cidade;
@Column(name = "nome", nullable = false)
private String nome;
@ManyToOne(optional=false)
@JoinColumn(name = "id_estado")
private Estado estado;
get e set ocultos
--------------------------------------------------------------------------
classe estado
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.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "tb_estado")
@SequenceGenerator(name = "estado_sequence", sequenceName = "seq_tb_estado", allocationSize = 1)
public class Estado implements Serializable {
private static final long serialVersionUID = -3243642346092867036L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "estado_sequence")
@Column(name = "id_estado")
private Long id;
@Column(name = "uf", nullable = false)
private String uf;
get e set ocultos
---------------------------------------------------------------------------------------------------------------------------------
meus daos:
interface DAO
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
public interface DAO<E,ID> extends Serializable {
public void create(E entity);
public E read(ID identity);
public Collection<E> read();
public void update(E entity);
public void delete(E entity);
-------------------------------------------------------------------------
PessoaDAO
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
import com.unimedcerrado.projeto.modelo.Pessoa;
@Stateless
public class PessoaDAO extends GenericDAO<Pessoa, Long> {
private static final long serialVersionUID = 3693934000644444548L;
@PersistenceContext(unitName = "primary")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Override
protected Class<Pessoa> getEntityClass() {
return Pessoa.class;
}
@Override
public void delete(Pessoa entity) {
String hql = "Delete From Pessoa e Where e.id = :id";
this.getEntityManager().createQuery(hql)
.setParameter("id", entity.getId()).executeUpdate();
}
public boolean existePessoaComRg(Pessoa entity) {
String hql = "Select e From Pessoa Where e.rg = :rgPagam";
if (entity.getId() != null) {
hql = hql + " and e.id != :idParam";
Query query = this.getEntityManager().createQuery(hql);
query.setParameter("rgParam", entity.getRg());
if (entity.getId() != null) {
query.setParameter("idParam", entity.getId());
}
return query.getResultList().size()>0;
}
return false;
}
-----------------------------------------------------------------------------------------------
cidadeDAO
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
@Stateless
public class CidadeDAO extends GenericDAO<Cidade, Long> {
private static final long serialVersionUID = 922388200167605258L;
@PersistenceContext(unitName = "primary")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Override
protected Class<Cidade> getEntityClass() {
return Cidade.class;
}
---------------------------------------------------------------------------------
estadoDAO
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.unimedcerrado.projeto.modelo.Cidade;
import com.unimedcerrado.projeto.modelo.Estado;
@Stateless
public class EstadoDAO extends GenericDAO<Estado, Long> {
private static final long serialVersionUID = 6953659285095057355L;
@PersistenceContext(unitName = "primary")
private EntityManager entityManager;
@Override
protected EntityManager getEntityManager() {
return this.entityManager;
}
@Override
protected Class<Estado> getEntityClass() {
return Estado.class;
}
@Override
public void delete(Estado entity) {
String hql = "Delete From Estado e Where e.id = :id";
this.getEntityManager().createQuery(hql)
.setParameter("id", entity.getId()).executeUpdate();
}
---------------------------------------------------------------------
genericDAO
import java.util.Collection;
import javax.persistence.EntityManager;
public abstract class GenericDAO<E, ID> implements DAO<E, ID> {
private static final long serialVersionUID = 1361504652223309748L;
protected abstract EntityManager getEntityManager();
protected abstract Class<E> getEntityClass();
protected String getQueryAll() {
return String.format("Select e From %s e", this.getEntityClass()
.getSimpleName());
}
@Override
public void create(E entity) {
this.getEntityManager().persist(entity);
}
@Override
public E read(ID identity) {
return this.getEntityManager().find(this.getEntityClass(), identity);
}
@SuppressWarnings("unchecked")
@Override
public Collection<E> read() {
return this.getEntityManager().createQuery(this.getQueryAll())
.getResultList();
}
@Override
public void update(E entity) {
this.getEntityManager().merge(entity);
}
@Override
public void delete(E entity) {
this.getEntityManager();
this.getEntityManager().remove(entity);
}
}
--------------------------------------------------------------------------------------------
Classes Serviço
estadoServico
import javax.ejb.EJB;
import com.unimedcerrado.projeto.modelo.Estado;
import com.unimedcerrado.projeto.persistencia.EstadoDAO;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public class EstadoServico extends GenericServico<Estado, Long> {
private static final long serialVersionUID = 930006390851601875L;
@EJB
private EstadoDAO dao;
@Override
public void create(Estado entity) throws NegocioException {
super.create(entity);
}
@Override
public void update(Estado entity) throws NegocioException {
super.update(entity);
}
@Override
public EstadoDAO getDAO() {
return this.dao;
}
}
----------------------------------------------------------------------------------------------
GenericServico
import java.util.Collection;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public abstract class GenericServico<E, ID> implements Servico<E, ID> {
private static final long serialVersionUID = -7536525219057881564L;
@Override
public void create(E entity) throws NegocioException {
this.getDAO().create(entity);
}
@Override
public E read(ID identity) {
return this.getDAO().read(identity);
}
@Override
public Collection<E> read() {
return this.getDAO().read();
}
@Override
public void update(E entity) throws NegocioException {
this.getDAO().update(entity);
}
@Override
public void delete(E entity) throws NegocioException {
this.getDAO().delete(entity);
}
}
-----------------------------------------------------------------------------------
servico
import java.io.Serializable;
import java.util.Collection;
import com.unimedcerrado.projeto.persistencia.DAO;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public interface Servico<E,ID> extends Serializable {
public DAO<E,ID> getDAO();
public void create(E entity) throws NegocioException;
public E read(ID identity);
public Collection<E> read();
public void update(E entity) throws NegocioException;
public void delete(E entity) throws NegocioException;
}
----------------------------------------------------------------------------------------
NegocioException
public class NegocioException extends RuntimeException{
private static final long serialVersionUID = -5493360949338751713L;
public NegocioException(String msg){
super(msg);
}
}
-----------------------------------------------------------------------------------
ManagedBeans:
GenericBean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import com.unimedcerrado.projeto.servico.Servico;
import com.unimedcerrado.projeto.servico.exception.NegocioException;
public abstract class GenericBean<E, ID, S extends Servico<E, ID>> implements
Serializable{
private static final long serialVersionUID = 1908229635425203875L;
private E formulario;
protected abstract S getServico();
@PostConstruct
protected abstract void inicializar();
public void adicionarMensagem(String mensagem) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(mensagem));
}
public void salvar() {
try {
this.getServico().create(this.getFormulario());
this.adicionarMensagem("Cadastrado com Sucesso!");
this.inicializar();
} catch (NegocioException e) {
this.adicionarMensagem(e.getMessage());
}
}
public void alterar() {
try {
this.getServico().update(this.getFormulario());
this.adicionarMensagem("Alteração realizada com Sucesso!");
this.inicializar();
} catch (NegocioException e) {
this.adicionarMensagem(e.getMessage());
}
}
public void remover(E entity) {
try {
this.getServico().delete(entity);
this.adicionarMensagem("Removido com Sucesso!");
} catch (NegocioException e) {
this.adicionarMensagem(e.getMessage());
}
}
public E getFormulario() {
return formulario;
}
public List<E> getEntidades() {
return new ArrayList<E>(this.getServico().read());
}
public void setFormulario(E formulario) {
this.formulario = formulario;
}
}
------------------------------------------------------------------------------------
PessoaBean
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.unimedcerrado.projeto.modelo.Pessoa;
import com.unimedcerrado.projeto.servico.PessoaServico;
@Named
@SessionScoped
public class PessoaBean extends GenericBean<Pessoa, Long, PessoaServico> {
private static final long serialVersionUID = 95889200604449740L;
@Inject
private PessoaServico servico;
@Override
protected PessoaServico getServico() {
return this.servico;
}
@Override
protected void inicializar() {
this.setFormulario(new Pessoa());
}
}
------------------------------------------------------------------
EstadoBean
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.unimedcerrado.projeto.modelo.Estado;
import com.unimedcerrado.projeto.servico.EstadoServico;
@Named
@SessionScoped
public class EstadoBean extends GenericBean<Estado, Long, EstadoServico> {
private static final long serialVersionUID = 4968510186149193943L;
@Inject
private EstadoServico servico;
@Override
protected EstadoServico getServico() {
return this.servico;
}
@Override
protected void inicializar() {
this.setFormulario(new Estado());
}
}
------------------------------------------------------------------------------------------------
meu xhtml
CadastroPessoas.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="/WEB-INF/template/Layout.xhtml">
<f:metadata>
<f:view action="#{pessoaBean.entidades}" />
</f:metadata>
<ui:define name="titulo">Sistema de Cadastros e Lançamentos</ui:define>
<ui:define name="corpo">
<p:panel header="Cadastro de Pessoas" rendered="true">
<h:form id="frmCadastroPessoas">
<p:messages />
<h:panelGrid columns="2" cellpadding="2" rendered="true"
style="width: 60%; text-align:left">
<p:outputLabel for="nome" value="Nome:" style="width: 100px;" />
<p:inputText style="width: 293px;" id="nome" required="true"
requiredMessage="O campo Nome é obrigatório!"
value="#{pessoaBean.formulario.nome}"
onchange="this.value = this.value.toUpperCase();"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:validateLength minimum="20" maximum="100" for="nome" />
</p:inputText>
<p:outputLabel for="endereco" value="Endereço:"
style="width: 100px;" />
<p:inputText style="width: 300px;" id="endereco" required="true"
requiredMessage="O campo Endereço é obrigatório!"
value="#{pessoaBean.formulario.endereco}"
onchange="this.value = this.value.toUpperCase();"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:validateLength minimum="20" maximum="200" for="nome" />
</p:inputText>
<p:outputLabel for="estado" value="UF:" />
<p:selectOneMenu id="estado" var="estado" required="false"
value="#{estadoBean.entidades}" style="width:85px"
requiredMessage="O campo UF é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="#{estado.uf}" />
<f:selectItems value="#"/>
</p:selectOneMenu>
<p:outputLabel for="cidade" value="Cidade:" />
<p:inputText id="cidade" required="true"
requiredMessage="O campo Cidade é obrigatório!"
value="#{pessoaBean.formulario.cidade}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="cep" value="Cep:" />
<p:inputMask mask="99.999-999" id="cep" required="true"
requiredMessage="O campo Cep é obrigatório!"
value="#{pessoaBean.formulario.cidade}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="rg" value="RG:" />
<p:inputMask mask="9999999" id="rg" required="true"
requiredMessage="O campo Rg é obrigatório!"
value="#{pessoaBean.formulario.rg}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="oexp" value="Orgão Expedidor:" />
<p:selectOneMenu id="oexp" required="true"
value="#{pessoaBean.formulario.orgExpedidor}" style="width:125px"
requiredMessage="O campo Orgão Expedidor é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="" />
<f:selectItem itemLabel="CGPI/DUREX/DPF"
itemValue="CGPI/DUREX/DPF" />
<f:selectItem itemLabel="SDS" itemValue="SDS" />
<f:selectItem itemLabel="SNJ" itemValue="SNJ" />
<f:selectItem itemLabel="SECC" itemValue="SECC" />
<f:selectItem itemLabel="SEJUSP" itemValue="SEJUSP" />
<f:selectItem itemLabel="SES/EST" itemValue="SES/EST" />
<f:selectItem itemLabel="SESP" itemValue="SESP" />
<f:selectItem itemLabel="SJS" itemValue="SJS" />
<f:selectItem itemLabel="SJTC" itemValue="SJTC" />
<f:selectItem itemLabel="SJTS" itemValue="SJTS" />
<f:selectItem itemLabel="SPTC" itemValue="SPTC" />
<f:selectItem itemLabel="SSP" itemValue="SSP" />
</p:selectOneMenu>
<p:outputLabel for="uf" value="UF:" />
<p:selectOneMenu id="uf" required="false"
value="#{pessoaBean.formulario.uf}" style="width:125px"
requiredMessage="O campo UF é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="" />
<f:selectItem itemLabel="AC" itemValue="AC" />
<f:selectItem itemLabel="AL" itemValue="AL" />
<f:selectItem itemLabel="AP" itemValue="AP" />
<f:selectItem itemLabel="AM" itemValue="AM" />
<f:selectItem itemLabel="BA" itemValue="BA" />
<f:selectItem itemLabel="CE" itemValue="CE" />
<f:selectItem itemLabel="DF" itemValue="DF" />
<f:selectItem itemLabel="ES" itemValue="ES" />
<f:selectItem itemLabel="GO" itemValue="GO" />
<f:selectItem itemLabel="MA" itemValue="MA" />
<f:selectItem itemLabel="MT" itemValue="MT" />
<f:selectItem itemLabel="MS" itemValue="MS" />
<f:selectItem itemLabel="MG" itemValue="MG" />
<f:selectItem itemLabel="PA" itemValue="PA" />
<f:selectItem itemLabel="PB" itemValue="PB" />
<f:selectItem itemLabel="PR" itemValue="PR" />
<f:selectItem itemLabel="PE" itemValue="PE" />
<f:selectItem itemLabel="PI" itemValue="PI" />
<f:selectItem itemLabel="RJ" itemValue="RJ" />
<f:selectItem itemLabel="RN" itemValue="RN" />
<f:selectItem itemLabel="RS" itemValue="RS" />
<f:selectItem itemLabel="RO" itemValue="RO" />
<f:selectItem itemLabel="RR" itemValue="RR" />
<f:selectItem itemLabel="SC" itemValue="SC" />
<f:selectItem itemLabel="SP" itemValue="SP" />
<f:selectItem itemLabel="SE" itemValue="SE" />
<f:selectItem itemLabel="TO" itemValue="TO" />
</p:selectOneMenu>
<p:outputLabel for="cpf" value="Cpf:" />
<p:inputMask mask="999.999.999-99" id="cpf" required="true"
requiredMessage="O campo Cpf é obrigatório!"
value="#{pessoaBean.formulario.cpf}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="estCivil" value="Estado Civil:" />
<p:selectOneMenu id="estCivil" required="true"
value="#{pessoaBean.formulario.estadoCivil}" style="width:125px"
requiredMessage="O campo Estado Civil é obrigatório!"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';">
<f:selectItem itemLabel="Selecione" itemValue="" />
<f:selectItem itemLabel="Solteiro(a)" itemValue="Solteiro(a)" />
<f:selectItem itemLabel="Casado(a)" itemValue="Casado(a)" />
<f:selectItem itemLabel="Divorciado(a)" itemValue="Divorciado(a)" />
<f:selectItem itemLabel="Viúvo(a)" itemValue="Viúvo(a)" />
<f:selectItem itemLabel="Companheiro(a)" itemValue="Companheiro(a)" />
</p:selectOneMenu>
<p:outputLabel for="telefone" value="Telefone:" />
<p:inputMask mask="(99) 9999-9999" id="telefone" required="true"
requiredMessage="O campo Telefone é obrigatório!"
value="#{pessoaBean.formulario.telefone}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
<p:outputLabel for="dn" value="Data Nascimento:" />
<p:calendar id="dn" size="12" locale="pt_BR" navigator="true"
pattern="dd/MM/yyyy"
value="#{pessoaBean.formulario.dataNascimento}" />
<p:outputLabel for="email" value="E-mail:" />
<p:inputText id="email" value="#{pessoaBean.formulario.email}"
onmouseover="this.style.backgroundColor='yellow';"
onmouseout="this.style.backgrounfColor='white';" />
</h:panelGrid>
<p:commandButton
rendered="#{manutencaoPessoaBean.formulario.id == null}"
update="@form" value="Cadastrar" icon="ui-icon-disk"
actionListener="#{pessoaBean.salvar()}" />
</h:form>
</p:panel>
</ui:define>
</ui:composition>
</html>
Adriana
Curtir tópico
+ 0
Responder
Clique aqui para fazer login e interagir na Comunidade :)