Problema com mapeamento hibernate

10 respostas
ThiagoWorldCoder

Olá pessoal!

Eu tenho uma pessoa que tem endereço e o id de pessoa que é chave extrangeira em endereço faz parte da chave primária de endereço (ou seja endereço fica com chave múltipla e uma das chaves é FK)… como eu faço para gerar o id de endereço sendo que ele vai depender do id de pessoa? Eu sei que eu poderia pesquisar o último id de endereco e depois acrescentar mais 1 diretamente pelo sql… mas acho que fica feio desse jeito né? Confiram também por favor se o mapeamento está ok?

exemplo:

public class Pessoa implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="IDPessoa")
	private Long idPessoa;

        // getters e setters / hashcode e equals
}
@Entity
@Table(name="tb_endereco")
public class Endereco implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@EmbeddedId
	private EnderecoPK enderecoPK;
        // getters e setters / hashcode e equals
@Embeddable
public class EnderecoPK implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@ManyToOne
	@JoinColumn(name="idPessoa")
	private Pessoa pessoa;
	
	private Long idEndereco;
        // getters e setters / hashcode e equals

Muito obrigado!

10 Respostas

A

cara,

da uma olhada nesse post, tem o que vc quer.

t+

ThiagoWorldCoder

blz, o post ajudou e deu certo, porém ainda existe um problema... :)

Esta Pessoa poderá ter vários telefones... e agora eu tenho uma lista de telefones em pessoa.. e também a pk de pessoa fará parte da chave composta de telefone... onde vai ter como chave composta (idTelefone e idPessoa, onde idPessoa é chave extrangeira)

Neste caso eu mapeei de maneira igual, porém colocando oneToMany e ManyToOne do lado inverso.. problema: Está salvando apenas um telefone.. seria importante salvar mais de um já que é uma lista.....

alguma ideia do que possa ser?
public class Pessoa implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="IDPessoa")
	private Long idPessoa;
	
	private String nome;
	
	private String sexo;
	
	private Date dataNascimento;
	
	private String numeroRG;
	
	private String numeroCPF;
	
	@OneToOne(cascade = CascadeType.ALL, mappedBy = "enderecoPK.pessoa", fetch = FetchType.LAZY)    
    private Endereco endereco;
	
	@OneToMany(cascade = CascadeType.ALL, mappedBy = "telefonePK.pessoa", fetch = FetchType.LAZY)    
    private Set<Telefone> telefones;
public class Telefone implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@EmbeddedId
	private TelefonePK telefonePK;
	
	private String ddd;
	
	private String numero;
@Embeddable
public class TelefonePK implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@ManyToOne(optional = false, fetch = FetchType.LAZY)
	@JoinColumn(name="idPessoa")
	private Pessoa pessoa;

	@Basic(optional = false)
	@Column(name = "idTelefone", nullable = false)
	private Long idTelefone;

}

valeu!!

A

cara,

vc realmente precisa na sua tabela de telefone, que idPessoa seja PK, não pode ser somente FK?

vou te passar um exemplo

import java.io.Serializable;
import javax.persistence.*;

import java.util.ArrayList;
import java.util.List;


/**
 * The persistent class for the teste2 database table.
 * 
 */
@Entity
@Table(name="teste2")
public class Teste2 implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer idteste2;

	private String nome;

	//bi-directional many-to-one association to Teste1
	@OneToMany(mappedBy="teste2", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	private List<Teste1> teste1s;

    public Teste2() {
    	this.teste1s = new ArrayList<Teste1>();
    }

	public Integer getIdteste2() {
		return this.idteste2;
	}

	public void setIdteste2(Integer idteste2) {
		this.idteste2 = idteste2;
	}

	public String getNome() {
		return this.nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public List<Teste1> getTeste1s() {
		return this.teste1s;
	}

	public void setTeste1s(List<Teste1> teste1s) {
		this.teste1s = teste1s;
	}	
}
package br.com.bingo.entity;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the teste1 database table.
 * 
 */
@Entity
@Table(name="teste1")
public class Teste1 implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private int idteste1;

	private String nome;

	//bi-directional many-to-one association to Teste2
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="teste2")
	private Teste2 teste2;

    public Teste1() {
    }

	public int getIdteste1() {
		return this.idteste1;
	}

	public void setIdteste1(int idteste1) {
		this.idteste1 = idteste1;
	}

	public String getNome() {
		return this.nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public Teste2 getTeste2() {
		return this.teste2;
	}

	public void setTeste2(Teste2 teste2) {
		this.teste2 = teste2;
	}
	
}
EntityManager entityManager = Persistence.createEntityManagerFactory("PersistUnit").createEntityManager();
		
		Teste2 teste2 = new Teste2();
		teste2.setNome("teste2");
		
		Teste1 teste11 = new Teste1();
		teste11.setNome("teste11");
		teste11.setTeste2(teste2);
		
		Teste1 teste12 = new Teste1();
		teste12.setNome("teste12");
		teste12.setTeste2(teste2);
		
		teste2.getTeste1s().add(teste11);
		teste2.getTeste1s().add(teste12);
		
		entityManager.getTransaction().begin();
		entityManager.persist(teste2);
		entityManager.getTransaction().commit();

espero q te ajude

t+

ThiagoWorldCoder

Muito obrigado pela ajuda, porém o idPessoa em telefone, precisa fazer parte da chave composta e também deve ser FK.
Cheguei a fazer o mapeamento só que inseriu 1 pessoa e 1 telefone só… faltou inserir 2 tels!

vlw!!

A

posta ai o q vc fez, para te dar uma ajudada.

t+

ThiagoWorldCoder

Esse é o código que estou testando pelo junit.. ele chega a criar blz.. só que não cria o segundo telefone que está na lista!

Calendar calendar = new GregorianCalendar();
		calendar.set(Calendar.DAY_OF_MONTH, 27);
		calendar.set(Calendar.MONTH, 2);
		calendar.set(Calendar.YEAR, 1985);
		
		pessoa = new Pessoa();
		pessoa.setNome("Thiago Prudente");
		pessoa.setNumeroCPF("06-03");
		pessoa.setNumeroRG("45941");
		pessoa.setDataNascimento(calendar.getTime());
		pessoa.setSexo("M");
		
		pessoa = pessoaDAO.save(pessoa);
		
		assertNotNull("Pessoa existe OK!",pessoa.getIdPessoa());
		
		pessoa = new Pessoa();
		pessoa.setNome("Thiago Prudente");
		pessoa.setNumeroCPF("06-03");
		pessoa.setNumeroRG("45941");
		pessoa.setDataNascimento(calendar.getTime());
		pessoa.setSexo("M");
		
		Endereco endereco = new Endereco();
		endereco.setBairro("olinda");
		endereco.setCep("38055400");
		endereco.setCidade("Uberaba");
		endereco.setComplemento("apto: 04");
		endereco.setNomeLogradouro("rua: sem saida");
		endereco.setNumero("278");
		endereco.setTipoLogradouro("ap");
		
		endereco.setEnderecoPK(new EnderecoPK());
		endereco.getEnderecoPK().setPessoa(pessoa);
		
		List<Telefone> telefones = new ArrayList<Telefone>();
		
		TelefonePK telefonePK = new TelefonePK();
		telefonePK.setPessoa(pessoa);
		
		Telefone telefone = new Telefone();
		telefone.setDdd("034");
		telefone.setNumero("12345678");
		telefone.setTelefonePK(telefonePK);
		telefones.add(telefone);
		
		telefone = new Telefone();
		telefone.setDdd("034");
		telefone.setNumero("9989545");
		telefone.setTelefonePK(telefonePK);
		telefones.add(telefone);	
		
		pessoa.setEndereco(endereco);
		pessoa.setTelefones(telefones);
				
		pessoa = pessoaFisicaDAO.save(pessoa);
		
		assertNotNull("Pessoa e endereco foram criados OK! ",pessoa.getEndereco());
A

cara,

posta as suas entidades, pessoa e telefone tbm

t+

ThiagoWorldCoder
ThiagoWorldCoder:
blz, o post ajudou e deu certo, porém ainda existe um problema... :)

Esta Pessoa poderá ter vários telefones... e agora eu tenho uma lista de telefones em pessoa.. e também a pk de pessoa fará parte da chave composta de telefone... onde vai ter como chave composta (idTelefone e idPessoa, onde idPessoa é chave extrangeira)

Neste caso eu mapeei de maneira igual, porém colocando oneToMany e ManyToOne do lado inverso.. problema: Está salvando apenas um telefone.. seria importante salvar mais de um já que é uma lista.....

alguma ideia do que possa ser?
public class Pessoa implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="IDPessoa")
	private Long idPessoa;
	
	private String nome;
	
	private String sexo;
	
	private Date dataNascimento;
	
	private String numeroRG;
	
	private String numeroCPF;
	
	@OneToOne(cascade = CascadeType.ALL, mappedBy = "enderecoPK.pessoa", fetch = FetchType.LAZY)    
    private Endereco endereco;
	
	@OneToMany(cascade = CascadeType.ALL, mappedBy = "telefonePK.pessoa", fetch = FetchType.LAZY)    
    private Set<Telefone> telefones;
public class Telefone implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@EmbeddedId
	private TelefonePK telefonePK;
	
	private String ddd;
	
	private String numero;
@Embeddable
public class TelefonePK implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@ManyToOne(optional = false, fetch = FetchType.LAZY)
	@JoinColumn(name="idPessoa")
	private Pessoa pessoa;

	@Basic(optional = false)
	@Column(name = "idTelefone", nullable = false)
	private Long idTelefone;

}

valeu!!

postado!

A

cara,

num projeto tenho essa situação como a sua, a unica coisa diferente é aqui na classe PK

@JoinColumn(name = "CHAVE_FK", referencedColumnName = "CHAVE_PK", insertable = false, updatable = false)
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)

ve te ajuda ai.

t+

Hebert_Coelho

Nesse post tem um exemplo de Mapeamento que eu acredito ser a sua dúvida.

@OneToMany e @ManyToOne Unidirecional e Bidirecional

Criado 28 de outubro de 2011
Ultima resposta 28 de out. de 2011
Respostas 10
Participantes 3