Olá senhores meu projeto está sem nenhum erro acusado pelo netbeans porém não consigo inserir nada no banco.
Como este erro precisa de uma análise minuciosa de OO já olhei bastante e estou deixando passar batido. Não consigo encontrar o que me impede de inserir no banco.
Pacote Util Classe HibernateUtility
package Util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtility {
private static final SessionFactory factory;
private static final ThreadLocal sessionThread = new ThreadLocal();
private static final ThreadLocal transactionThread = new ThreadLocal();
public static Session getSession() {
Session session = (Session) sessionThread.get();
if ((session == null) || (!(session.isOpen()))) {
session = factory.openSession();
sessionThread.set(session);
}
return ((Session) sessionThread.get());
}
public static void closeSession() {
Session session = (Session) sessionThread.get();
if ((session != null) && (session.isOpen())) {
sessionThread.set(null);
session.close();
}
}
public static void beginTransaction() {
Transaction transaction = getSession().beginTransaction();
transactionThread.set(transaction);
}
public static void commitTransaction() {
Transaction transaction = (Transaction) transactionThread.get();
if ((transaction != null) && (!(transaction.wasCommitted())) && (!(transaction.wasRolledBack()))) {
transaction.commit();
transactionThread.set(null);
}
}
public static void rollbackTransaction() {
Transaction transaction = (Transaction) transactionThread.get();
if ((transaction != null) && (!(transaction.wasCommitted())) && (!(transaction.wasRolledBack()))) {
transaction.rollback();
transactionThread.set(null);
}
}
static {
try {
factory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
}
Pacote Util Interface DaoGenerico
package Util;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
*
* @author Paulo
*/
public interface DaoGenerico<T, ID extends Serializable> {
public Class<T> getObjectClass();
public T merge(T objeto);
public void delete(T objeto);
public void deleteItem(T objeto);
public List<T> getAll();
public List<T> getCriterio(String subClazz, Map<String, Object> filtrosConsulta, int tipoConsulta);
public T getById(Serializable id);
public List<T> consultaHQL(String consulta);
public void cancel();
}
Pacote Util Classe DaoGenericoImp
package Util;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
/**
*
* @author Paulo
*/
public class DaoGenericoImp<T, ID extends Serializable> implements DaoGenerico<T, ID> {
private final Class<T> oClass;
public DaoGenericoImp() {
this.oClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@Override
public Class<T> getObjectClass() {
return this.oClass;
}
@Override
public T merge(T objeto) {
try {
Object obj = null;
HibernateUtility.beginTransaction();
obj = HibernateUtility.getSession().merge(objeto);
HibernateUtility.commitTransaction();
HibernateUtility.closeSession();
return (T) obj;
} catch (HibernateException hibernateException) {
cancel();
throw hibernateException;
}
}
@Override
public void delete(T objeto) {
try {
HibernateUtility.beginTransaction();
HibernateUtility.getSession().delete(objeto);
HibernateUtility.commitTransaction();
HibernateUtility.closeSession();
} catch (HibernateException hibernateException) {
cancel();
throw hibernateException;
}
}
@Override
public void deleteItem(T objeto) {
try {
HibernateUtility.beginTransaction();
HibernateUtility.getSession().delete(objeto);
} catch (HibernateException hibernateException) {
cancel();
throw hibernateException;
}
}
@Override
public List<T> getAll() {
try {
List list = HibernateUtility.getSession().createCriteria(oClass).list();
//HibernateUtility.closeSession();
return (List<T>) list;
} catch (HibernateException hibernateException) {
cancel();
throw hibernateException;
}
}
@Override
public T getById(Serializable id) {
try {
return (T) HibernateUtility.getSession().get(oClass, id);
} catch (HibernateException hibernateException) {
cancel();
throw hibernateException;
}
}
@Override
public List<T> getCriterio(String subClazz, Map<String, Object> filtrosConsulta, int tipoConsulta) {
List<T> lista = new ArrayList<T>();
Set entradas = filtrosConsulta.entrySet();
try {
Criteria crit = HibernateUtility.getSession().createCriteria(oClass);
if (subClazz == null) {
for (Iterator it = entradas.iterator(); it.hasNext();) {
Entry object = (Entry) it.next();
if (object.getValue() instanceof Enum) {
crit.add(Restrictions.eq(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 0) {
crit.add(Restrictions.ilike(object.getKey().toString(), "%" + object.getValue() + "%"));
} else if (tipoConsulta == 1) {
crit.add(Restrictions.eq(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 2) {
crit.add(Restrictions.gt(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 3) {
crit.add(Restrictions.ge(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 4) {
crit.add(Restrictions.lt(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 5) {
crit.add(Restrictions.le(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 2) {
crit.add(Restrictions.ne(object.getKey().toString(), object.getValue()));
}
}
} else {
for (Iterator it = entradas.iterator(); it.hasNext();) {
Entry object = (Entry) it.next();
//crit.createCriteria(subClazz).add(Restrictions.ilike(object.getKey().toString(), "%" + object.getValue() + "%"));
if (object.getValue() instanceof Enum) {
} else if (tipoConsulta == 0) {
crit.createCriteria(subClazz).add(Restrictions.ilike(object.getKey().toString(), "%" + object.getValue() + "%"));
} else if (tipoConsulta == 1) {
crit.createCriteria(subClazz).add(Restrictions.eq(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 2) {
crit.createCriteria(subClazz).add(Restrictions.gt(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 3) {
crit.createCriteria(subClazz).add(Restrictions.ge(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 4) {
crit.createCriteria(subClazz).add(Restrictions.lt(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 5) {
crit.createCriteria(subClazz).add(Restrictions.le(object.getKey().toString(), object.getValue()));
} else if (tipoConsulta == 2) {
crit.createCriteria(subClazz).add(Restrictions.ne(object.getKey().toString(), object.getValue()));
}
}
}
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
crit.setMaxResults(20);
lista = (List<T>) crit.list();
//HibernateUtility.closeSession();
return lista;
} catch (HibernateException hibernateException) {
cancel();
throw hibernateException;
}
}
@Override
public List<T> consultaHQL(String consulta) {
return (List<T>) HibernateUtility.getSession().createQuery(consulta).list();
}
@Override
public void cancel() {
HibernateUtility.rollbackTransaction();
HibernateUtility.closeSession();
}
}
Pacote Modelo Classe Paciente
package Modelo;
import Modelo.Location.Endereco;
import Modelo.Ficha.Ficha;
import Modelo.Ficha.FichaPeriodontoal;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
*
* @author Paulo
*/
@Entity
public class Paciente implements Serializable {
@Id
@GeneratedValue
@Column(name="id_paciente")
private long id;
private String nome;
private String telefone;
private String celular;
@OneToOne(mappedBy="paciente")
@Cascade(CascadeType.ALL)
private Endereco endereco;
private String email;
private Timestamp nascimento;
private String cpf;
private String sexo;
@OneToOne(mappedBy="paciente")
@Cascade(CascadeType.ALL)
private Ficha fichaGeral;
@OneToOne(mappedBy="paciente")
@Cascade(CascadeType.ALL)
private FichaPeriodontoal fichaPeriodontal;
@OneToMany(mappedBy="paciente", fetch= FetchType.LAZY)
@Cascade(CascadeType.ALL)
private List<Tratamento> tratamentos;
public long getId() {
return id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getNascimento() {
return nascimento;
}
public void setNascimento(Timestamp nascimento) {
this.nascimento = nascimento;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public Ficha getFichaGeral() {
return fichaGeral;
}
public void setFichaGeral(Ficha fichaGeral) {
this.fichaGeral = fichaGeral;
}
public FichaPeriodontoal getFichaPeriodontal() {
return fichaPeriodontal;
}
public void setFichaPeriodontal(FichaPeriodontoal fichaPeriodontal) {
this.fichaPeriodontal = fichaPeriodontal;
}
public List<Tratamento> getTratamentos() {
return tratamentos;
}
public void setTratamentos(List<Tratamento> tratamentos) {
this.tratamentos = tratamentos;
}
}
Pacote Dao Interface PacienteDao
package Dao;
import Modelo.Paciente;
import Util.DaoGenerico;
import java.util.List;
/**
*
* @author Paulo
*/
public interface PacienteDao extends DaoGenerico<Paciente, Long> {
public List consultar();
}
Pacote Dao classe PacienteDaoImp
package Dao;
import Modelo.Paciente;
import Util.DaoGenericoImp;
import Util.HibernateUtility;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
/**
*
* @author Paulo
*/
public class PacienteDaoImp extends DaoGenericoImp<Paciente, Long> implements PacienteDao {
@Override
public List consultar() {
List lista = new ArrayList();
Criteria crit = HibernateUtility.getSession().createCriteria(Paciente.class);
lista = (List) crit.list();
return lista;
}
}
Pacote Bean Classe PacienteBean
package Controle;
import Dao.PacienteDao;
import Dao.PacienteDaoImp;
import Modelo.Paciente;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* @author Paulo
*/
@ManagedBean
@SessionScoped
public class PacienteBean implements Serializable {
private Paciente paciente = new Paciente();
List <Paciente> pacientes = new ArrayList();
private PacienteDao dao = new PacienteDaoImp();
public PacienteBean() {
pacientes = dao.consultar(); // busca no banco todos os registros e popula a lista de pacientes
}
public void salvar(){
dao.merge(paciente); // salvando no banco de dados
paciente = new Paciente(); // criando um novo objeto para caso for inserir novamente
pacientes = dao.consultar(); //busca os dados no banco após salvar para apresentar na tabela
}
public void editar(){
paciente = dao.getById(paciente.getId()); // busca no banco qual registro que vai ser alterado.
}
public void deletar(){
dao.delete(paciente); // deleta do banco o paciente que está no objeto paciente, que foi setado na view.
pacientes = dao.consultar(); // busca os dados no banco após excluir para apresentar na tabela
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
public List getPacientes() {
return pacientes;
}
public void setPacientes(List pacientes) {
this.pacientes = pacientes;
}
}
Pagina JSF Paciente
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="./template.xhtml"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<ui:define name="conteudo">
<h:form id="form">
<p:panel header="Cadastro de Pacientes" id="panel">
<h:panelGrid columns="2">
<h:outputLabel value="Nome:" for="nome"/>
<p:inputText id="nome" value="#{pacienteBean.paciente.nome}" maxlength="40" size="40"/>
<h:outputLabel value="E-mail:" for="email"/>
<p:inputText id="email" value="#{pacienteBean.paciente.email}" maxlength="40" size="40"/>
<h:outputLabel value="Rua: " for="rua"/>
<p:inputText id="rua" value="#{pacienteBean.paciente.endereco.rua}" maxlength="40" size="40"/>
<h:outputLabel value="Bairro:" for="bairro"/>
<p:inputText id="bairro" value="#{pacienteBean.paciente.endereco.bairro}" maxlength="40" size="40"/>
<h:outputLabel value="CEP:" for="cep"/>
<p:inputMask id="cep" value="#{pacienteBean.paciente.endereco.cep}" mask="99999-999" size="40"/>
<h:outputLabel value="Celular:" for="celular"/>
<p:inputMask id="celular" value="#{pacienteBean.paciente.celular}" mask="(99) 9999 - 9999" size="40"/>
<h:outputLabel value="CPF:" for="cpf"/>
<p:inputMask id="cpf" value="#{pacienteBean.paciente.cpf}" mask="[CPF removido]" size="40"/>
<h:outputLabel value="Data de Nascimento:" for="nascimento"/>
<p:calendar id="nascimento" value="#{pacienteBean.paciente.nascimento}" pattern="dd/mm/yyyy" size="40" effect="slideDown"/>
<p:commandButton id="btnSalvar" value="Salvar" action="#{pacienteBean.salvar()}" update="form, tabela"/>
</h:panelGrid>
<p:dataTable id="tabela" value="#{pacienteBean.pacientes}" var="pac" emptyMessage="Nehum registro incluído" paginator="true" rows="10">
<f:facet name="header">
Lista de Pacientes
</f:facet>
<p:column headerText="Nome" style="text-align: center">
<h:outputText value="#{pac.nome}"/>
</p:column>
<p:column headerText="E-mail" style="text-align: center">
<h:outputText value="#{pac.email}"/>
</p:column>
<p:column headerText="Endereco" style="text-align: center">
<h:outputText value="#{pac.rua}"/>
</p:column>
<p:column headerText="Celular" style="text-align: center">
<h:outputText value="#{pac.celular}"/>
</p:column>
<p:column headerText="CPF" style="text-align: center">
<h:outputText value="#{pac.cpf}"/>
</p:column>
<p:column headerText="Nascimento" style="text-align: center">
<h:outputText value="#{pac.nascimento}"/>
</p:column>
<p:column headerText="Sexo" style="text-align: center">
<h:outputText value="#{pac.sexo}"/>
</p:column>
</p:dataTable>
</p:panel>
</h:form>
</ui:define>
</ui:composition>
Bom o código todo é este, consigo gerar o banco normalmente, a classe está mapeada no xml do hibernate.
Tudo aparentemente normal mas não funciona, deve ser alguma coisa besta mas que estou deixando passar batido…,
Me ajudem a encontrar!
Ps: quando mando rodar a página renderiza normalmente com todos os campos tudo muito lindo…
preencho tudo mando salvar e nada de aparecer no banco ou muito menos na tabela abaixo.