Herança + Hibernate + JSF

4 respostas
M

Estou com o seguinte problema. Tenho uma classe pessoa e uma classe paciente que deriva de pessoa. Porém quando tento salvar me dá erro, e o erro é no select para listar as pessoas, retornando que o valor endereço está nulo.
Segue abaixo as classes:

Classe Pessoa:
package br.com.pew.model;

import java.io.Serializable;

import java.util.Date;

import javax.persistence.DiscriminatorColumn;

import javax.persistence.DiscriminatorType;

import javax.persistence.GeneratedValue;

import javax.persistence.Entity;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.Inheritance;

import javax.persistence.InheritanceType;

import javax.persistence.Table;

import javax.persistence.UniqueConstraint;
@Entity

@Table(name = pessoa)

@Inheritance(strategy = InheritanceType.JOINED)

public abstract class Pessoa implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer Id;
private String Nome;
private String Endereco;
private String Cidade;
private String Estado;
private String Cep;
private String Bairro;
private String Telefone;
private String Celular;
private String Complemento;
private String CPF;
private String RG;	
private Date Nascimento;
public String getNome() {
	return Nome;
}
public void setNome(String nome) {
	Nome = nome;
}
public String getEndereco() {
	return Endereco;
}
public void setEndereco(String endereco) {
	Endereco = endereco;
}
public String getCidade() {
	return Cidade;
}
public void setCidade(String cidade) {
	Cidade = cidade;
}
public String getEstado() {
	return Estado;
}
public void setEstado(String estado) {
	Estado = estado;
}
public String getCep() {
	return Cep;
}
public void setCep(String cep) {
	Cep = cep;
}
public String getBairro() {
	return Bairro;
}
public void setBairro(String bairro) {
	Bairro = bairro;
}
public String getCelular() {
	return Celular;
}
public void setCelular(String celular) {
	Celular = celular;
}
public String getTelefone() {
	return Telefone;
}
public void setTelefone(String telefone) {
	Telefone = telefone;
}
public String getComplemento() {
	return Complemento;
}
public void setComplemento(String complemento) {
	Complemento = complemento;
}
public String getCPF() {
	return CPF;
}
public void setCPF(String cPF) {
	CPF = cPF;
}
public String getRG() {
	return RG;
}
public void setRG(String rG) {
	RG = rG;
}
public Date getNascimento() {
	return Nascimento;
}
public void setNascimento(Date nascimento) {
	Nascimento = nascimento;
}
public Integer getId() {
	return Id;
}
public void setId(Integer id) {
	Id = id;
}

}

Classe Paciente:

package br.com.pew.model;

import java.io.Serializable;

import javax.persistence.DiscriminatorValue;

import javax.persistence.Entity;

import javax.persistence.PrimaryKeyJoinColumn;

import javax.persistence.Table;
@Entity

@Table(name=paciente)

@PrimaryKeyJoinColumn(name=id)

public class Paciente extends Pessoa implements Serializable {
private String codSUS;

public String getCodSUS() {
	return codSUS;
}

public void setCodSUS(String codSUS) {
	this.codSUS = codSUS;
}

}

Paciente DAO

package br.com.pew.dao;

import java.util.List;

import org.hibernate.Criteria;

import org.hibernate.FlushMode;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.context.internal.ManagedSessionContext;

import org.primefaces.model.SelectableDataModel;
import br.com.pew.model.Paciente;

import br.com.pew.model.Pessoa;

import br.com.pew.util.HibernateUtil;
public class PacienteDAO {

SessionFactory sf = HibernateUtil.getSessionFactory();

Transaction trans;

Session currentSession;

private List list;
public void addPaciente (Paciente pac){
	try{
		currentSession = sf.openSession();
		currentSession.setFlushMode(FlushMode.MANUAL);
		
		ManagedSessionContext.bind(currentSession);
		currentSession.beginTransaction();
		
		Paciente paciente = new Paciente();
		
		paciente.setBairro(pac.getBairro());
		paciente.setCelular(pac.getCelular());
		paciente.setCep(pac.getCep());
		paciente.setCidade(pac.getCidade());
		paciente.setComplemento(pac.getComplemento());
		paciente.setCPF(pac.getCPF());
		paciente.setEndereco(pac.getEndereco());
		paciente.setEstado(pac.getEstado());			
		paciente.setNascimento(pac.getNascimento());
		paciente.setNome(pac.getNome());
		paciente.setRG(pac.getRG());
		paciente.setTelefone(pac.getTelefone());
		paciente.setCodSUS(pac.getCodSUS());
		
		currentSession.save(paciente);
		ManagedSessionContext.unbind(sf);

		currentSession.flush();
		currentSession.getTransaction().commit();
		
	}catch(Exception e){
		currentSession.getTransaction().rollback();
		e.printStackTrace();
	}finally{
		currentSession.close();
	}
}
public void AtualizaPaciente(Paciente pac){
	try{
		currentSession = sf.openSession();
		currentSession.setFlushMode(FlushMode.MANUAL);

		ManagedSessionContext.bind(currentSession);
		currentSession.beginTransaction();
		
		Paciente paciente = new Paciente();
		
		paciente.setBairro(pac.getBairro());
		paciente.setCelular(pac.getCelular());
		paciente.setCep(pac.getCep());
		paciente.setCidade(pac.getCidade());
		paciente.setComplemento(pac.getComplemento());
		paciente.setCPF(pac.getCPF());
		paciente.setEndereco(pac.getEndereco());
		paciente.setEstado(pac.getEstado());
		paciente.setId(pac.getId());
		paciente.setNascimento(pac.getNascimento());
		paciente.setNome(pac.getNome());
		paciente.setRG(pac.getRG());
		paciente.setTelefone(pac.getTelefone());
		
		currentSession.update(paciente);
		ManagedSessionContext.unbind(sf);

		currentSession.flush();
		currentSession.getTransaction().commit();			
		
		
	}catch(Exception e){
		currentSession.getTransaction().rollback();
		e.printStackTrace();
	}finally{
		currentSession.close();
	}
}
public void RemoverPaciente(Paciente pac){
	try{
		currentSession = sf.openSession();
		currentSession.setFlushMode(FlushMode.MANUAL);

		ManagedSessionContext.bind(currentSession);
		currentSession.beginTransaction();
		
		currentSession.delete(pac);
		
		ManagedSessionContext.unbind(sf);

		currentSession.flush();
		currentSession.getTransaction().commit();
	}catch(Exception e){
		currentSession.getTransaction().rollback();
		e.printStackTrace();
	}finally{
		currentSession.close();
	}
}
public List<Paciente> getList(){
	currentSession = sf.openSession();
	currentSession.setFlushMode(FlushMode.MANUAL);
	
	ManagedSessionContext.bind(currentSession);
	
	Criteria cri = currentSession.createCriteria(Pessoa.class);
	this.list = cri.list();
	return list;
}
public Integer getRowKey(Paciente pac){
	return pac.getId();
}

}

Paciente Bean

package br.com.pew.controller;

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.SessionScoped;

import javax.faces.context.FacesContext;
import org.hibernate.Session;

import org.hibernate.context.spi.CurrentSessionContext;

import org.primefaces.event.RowEditEvent;

import org.primefaces.event.SelectEvent;
import br.com.pew.util.HibernateUtil;

import br.com.pew.dao.PacienteDAO;

import br.com.pew.model.Paciente;

@SessionScoped
@ManagedBean
public class PacienteBean {

private Paciente paciente = new Paciente();
private PacienteDAO pacienteDao = new PacienteDAO();
private List<Paciente> listarPaciente;
private Paciente selectPaciente;

public Paciente getPaciente(){
	return paciente;
}

public String Adicionar(){
	pacienteDao.addPaciente(paciente);
	return "cadPaciente";
}
public String Atualizar(){
	pacienteDao.AtualizaPaciente(selectPaciente);
	return "cadPaciente";
}
public String Remover (){
	pacienteDao.RemoverPaciente(paciente);
	return "cadPaciente";
}
public List listaPaciente(){
	listarPaciente = pacienteDao.getList();
	return listarPaciente;
}
public void setSelectPaciente(Paciente selectPaciente){
	this.selectPaciente = selectPaciente;
}
public Paciente getSelectPaciente(){
	return selectPaciente;
}

}

Se alguém puder me ajudar, tenho uma certa urgência. Obrigado.

4 Respostas

S

Boa noite,

Você fez o mapeamento de suas entidades no arquivo hibernate.cfg.xml ?

Outra dica é, se acaso você MYSQL como banco de dados nativo, mude para SQLServer, pois o MYSQL possui alguns bugs com relação a ponteiros nulos!

M

Segue abaixo o hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8" ?> org.gjt.mm.mysql.Driver jdbc:mysql://localhost:3306/ProntuarioWeb root 1234 ProntuarioWeb org.hibernate.dialect.MySQLDialect update

e também o properties, pois só com o cfg.xml não conseguia sucesso na conexão

################################################################################

Copyright © 2007, Red Hat Middleware, LLC. All rights reserved.

This copyrighted material is made available to anyone wishing to use, modify,#

copy, or redistribute it subject to the terms and conditions of the GNU

Lesser General Public License, v. 2.1. This program is distributed in the

hope that it will be useful, but WITHOUT A WARRANTY; without even the implied#

warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU

Lesser General Public License for more details. You should have received a

copy of the GNU Lesser General Public License, v.2.1 along with this

distribution; if not, write to the Free Software Foundation, Inc.,

51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

Red Hat Author(s): Steve Ebersole

################################################################################
hibernate.dialect org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class org.gjt.mm.mysql.Driver
hibernate.connection.url jdbc:mysql://localhost:3306/ProntuarioWeb
hibernate.connection.username root
hibernate.connection.password=1234
hibernate.connection.isolation ${jdbc.isolation}

hibernate.connection.pool_size 5

hibernate.show_sql true
hibernate.current_session_context_class=org.hibernate.context.ManagedSessionContext
hibernate.connection.autocommit=false
hibernate.hbm2ddl.auto=update
hibernate.format_sql true

hibernate.max_fetch_depth 5

hibernate.cache.region_prefix hibernate.test
hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider

Agora, sobre o BD, não posso trocar, faz parte do projeto BD MySQL. E realmente ele nem cria as tabelas, como seria o normal pelo hibernate

ThalitaPinheiro

Cara, quando você for postar pedaços de código, usa o a tag “code”…

Assim fica muito ruim de ler… =(

M

@ThalitaPinheiro:
Cara, quando você for postar pedaços de código, usa o a tag “code”…

Assim fica muito ruim de ler… =(

Desculpe Thalita, depois que vi as Tags. Mas Obrigado pela dica.

Aproveitando, consegui resolver este problema. Tinha esquecido de olhas o HibernateUtil, e quando vi notei que as classes não estavam apontadas lá, no addAnnotationClass.

Criado 3 de novembro de 2013
Ultima resposta 5 de nov. de 2013
Respostas 4
Participantes 3