@ManyToOne n salva fk

Bom dia estou com o seguinte problema:

  • Tenho a tabela paciente e a tabela telefone
  • 1 paciente tem uma lista de telefones

Segue as variáveis:

@Entity
Paciente

@OneToMany(mappedBy = "paciente", orphanRemoval = true, targetEntity = Telefone.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Telefone> telefones;
@Entity 
Telefone

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "idPaciente")
private Paciente paciente;

Meu generic dao:

public void salvar(Entidade entidade) {
	Session sessao = ConnectionFactory.getFabricaDeSessoes().openSession();
	Transaction transacao = null;
	
	try {
		transacao = sessao.beginTransaction();
		sessao.save(entidade);
		transacao.commit();
	} catch (RuntimeException erro) {
		if (transacao != null) {
			transacao.rollback();
		}
		
		throw erro;
	} finally {
		sessao.close();
	}
}

Metodo que estou utilizando para testar persistencia:

Paciente paciente = new Paciente();
paciente.setNome("Henrique");
paciente.setCpf("186.200.191-23");
paciente.setDataNascimento(new Date(System.currentTimeMillis()));
paciente.setSexo(Sexo.MASCULINO);
paciente.setEmail("henrique@gmail.com");
paciente.setEndereco(new Endereco("88131-743", "Braulina Goulart", "48", "RioGrande", "", "SC"));
paciente.setTipoSanguineo("O+");

List<Telefone> telefones = new ArrayList();
telefones.add(new Telefone("(48)996850323", "Celular", "João", "Irmão", true));
telefones.add(new Telefone("(48)996850323", "Celular", "Henrique", "Pai", true));

paciente.setTelefones(telefones);

dao.salvar(paciente);

Do jeito q ta salva o telefone e o paciente, mais la na tabela de telefone o idPaciente fica null, ai quando busco por paciente n vem os telefones

Vc precisa adicionar o paciente aos telefones criados:

Altere o construtor para receber o paciente

Paciente paciente = new Paciente();
// ...

List<Telefone> telefones = new ArrayList();
telefones.add(new Telefone(paciente, "(48)996850323", "Celular", "João", "Irmão", true));
telefones.add(new Telefone(paciente, "(48)996850323", "Celular", "Henrique", "Pai", true));

Para facilitar identificação de erros, coloque a coluna paciente na tabela telefone como not null

1 curtida

bah , que vacilo, achei que o hibernate ja fazia isso XD

Bom dia,
estou tendo outro problema, agora na hora de pesquisar

metodo que pesquiso os telefones de um determinado paciente

public List<Telefone> getTelefonesPaciente(int id) {
        Session sessao = ConnectionFactory.getFabricaDeSessoes().openSession();
        try {
            Query crit = sessao.createQuery("Select t FROM Telefone as t where t.paciente =:idPessoa");
            crit.setParameter("idPessoa", id);
            return crit.getResultList();
        } catch (RuntimeException erro) {
            throw erro;
        } finally {
            sessao.close();
        }
    }


 public void testGetTelefonesPaciente() {
        for (Telefone t : dao.getTelefonesPaciente(5)) {
            System.out.println(t.getNome());
        }
    }

Erro:
Tests in error:
testGetTelefonesPaciente(br.com.clinica.dao.banco.impl.TelefoneDaoImplTest): org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer br.com.clinica.domain.Paciente.id] by reflection for persistent property [br.com.clinica.domain.Paciente#id] : 5

Tente mudar sua consulta para:

SELECT t FROM Telefone AS t WHERE t.paciente.id = :idPessoa
1 curtida

eita, na mosca de novo hehe
funcinou certinho vlw!

1 curtida