Problemas com Chave composta

7 respostas
worldsoft

Galera já procurei na internet sobre esse assunto , achei bastante coisa mais minha dúvida ainda persiste, estou recorrendo a vocês para me dar uma luz.
O problema é o seguinte:

Tenho um relacionamento de N:N com duas tabelas uma chamada Phone e outra PhoneType, na classe Phone estou fazendo o seguinte:

@Entity
public class Phone {
	private Long id;
	private int ddi;
	private int ddd;
	private String phone;
	private List<PhoneType> phoneTypes;
        
        @ManyToMany	
	@JoinTable (
			name="phone_typePhone_list",			
			joinColumns=@JoinColumn(insertable=false, updatable=false),
			inverseJoinColumns=@JoinColumn(insertable=false, updatable=false))	
	public List<PhoneType> getPhoneType() {
		return phoneTypes;
	}
        ....//getters e setters
}

Nessa tablela “Phone_TypePhone_List” tenho dois atributos o id da classe Phone e o id da classe PhoneType, mais do jeito que está posso inserir nessa tabela as seguintes id:

Phone.id = 1
PhoneType.id =1

Phone.id = 1
PhoneType.id =2

Phone.id = 1
PhoneType.id =1

O que não seria o correto, pois se já tenho os id 1-1 não posso salva-lo novamente. Alguma sujestão?

7 Respostas

luxu

como vc relacionou as 2 tabelas? pq no caso esse relacionamento tem q ser chave composta, ou seja, na 3ª Tabela elas serão chaves primarias tb, se for assim elas nunca se repetirão e elas não podem ser auto-incremento, ou seja, vc terá q informar na tabela nova as duas chaves e não deixar q o banco o faça, axo q seria isso…

worldsoft

Correto, seria isso mesmo…

Quando crio o relacionamento o hibernate cria esta 3° tabela com dois campos, os id de cada objeto Phone e PhoneType, só que estes campos são criados apenas como fk e não como pk, gostaria de saber como fazer isso pelo hibernate?

luxu

axo vc tem q usar as anotações pra isso, pois nunca criei o banco pelo hibernate e sim direto no mysql via ferramentas…post suas classes pra dar uma olhada…

worldsoft

Correto, gostaria de usar as anotações para isso, segue classes:

import java.util.List;

import javax.persistence.*;

@Entity
public class Phone {
	private Long id;
	private int ddi;
	private int ddd;
	private String phone;
	private List<PhoneType> phoneTypes;
		
	@Id
	@SequenceGenerator(name="Sequence_Phone", sequenceName="Sequence_Phone", initialValue=1 )
	@GeneratedValue(strategy=GenerationType.AUTO, generator="Sequence_Phone")
	public Long getId() {
		return id;
	}
	
	public void setId(Long id) {
		this.id = id;
	}
	
	@Column(length=3, nullable=false)
	public int getDdi(){
		return this.ddi;
	}
	
	public void setDdi(int ddi){
		this.ddi = ddi;
	}
	
	@Column(length=3, nullable=false)
	public int getDdd() {
		return ddd;
	}
	
	public void setDdd(int ddd) {
		this.ddd = ddd;
	}
	
	@Column(length=8, nullable=false)
	public String getPhone() {
		return phone;
	}
	
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	@ManyToMany	
	@JoinTable (
			name="Phone_TypePhone_List",					
			joinColumns=@JoinColumn(insertable=false, updatable=false),
			inverseJoinColumns=@JoinColumn(insertable=false, updatable=false))	
	public List<PhoneType> getPhoneType() {
		return phoneTypes;
	}
	
	public void setPhoneType(List<PhoneType> phoneType) {
		this.phoneTypes = phoneType;
	}	
	
	public String toString(){
		return "DDI: "+ ddi +
			   " DDD: " + ddd +
			   " Fone: " + this.phone;
	}
	
}
package br.com.tsoftnet.atlas.administration.models;

import javax.persistence.*;

@Entity
public class PhoneType implements Type {
	private Long id;
	private String description;
		
	@Id
	@SequenceGenerator(name="Sequence_PhoneType", sequenceName="Sequence_PhoneType", initialValue=1)
	@GeneratedValue(strategy=GenerationType.AUTO, generator="Sequence_PhoneType")
	public Long getId() {
		return id;
	}
	
	public void setId(Long id) {
		this.id = id;
	}
	
	@Column(length=30, nullable=false)
	public String getDescription() {
		return this.description;
	}
	
	public void setDescription(String description) {
		this.description = description;
	}
			
	public String toString(){
		return this.description;
	}
	
}

Código que o hibernate cria no postgre:

CREATE TABLE phone_typephone_list
(
  phone_id bigint NOT NULL,
  phonetype_id bigint NOT NULL,
  CONSTRAINT fk59b4729a702276ff FOREIGN KEY (phone_id)
      REFERENCES phone (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk59b4729a8f31be5f FOREIGN KEY (phonetype_id)
      REFERENCES phonetype (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);
ALTER TABLE phone_typephone_list OWNER TO atlas;
worldsoft

Luxu criando as tabelas via ferramenta sei que funciona normalmente, mais como ficaria o relacionamento das classes, teria que criar uma 3° classe para persistir esses dados?

luxu

agora q vi q a classe PHONE_TYPE herda da PHONE certo? nunca usei assim e naum posso falar nd…

worldsoft

E como você faria isso?

Criado 14 de junho de 2011
Ultima resposta 14 de jun. de 2011
Respostas 7
Participantes 2