Amigos ao persistir o objeto cidade com relacionamento com o objeto uf esta dando erro, no relacionamento esta buscando a proxima chave da cidade e nao o id do objeto que esta setado.
Classe UF
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
@Entity
@Table(name = "UF")
@SequenceGenerator(name = "UF_ID_SEQ", sequenceName = "UF_ID_SEQ", allocationSize = 1, initialValue = 0)
public class Uf implements Serializable {
private static final long serialVersionUID = 1L;
// Atributos da classe
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "UF_ID_SEQ")
@Column(name = "ID", nullable = false)
private long id;
@Column(name = "codigo")
private String codigo;
@Column(name = "sigla")
private String sigla;
@Column(name = "nome")
private String nome;
public Uf() {
}
// Gets and Sets
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
// Metodos adcionais
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((sigla == null) ? 0 : sigla.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Uf other = (Uf) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
if (id != other.id)
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (sigla == null) {
if (other.sigla != null)
return false;
} else if (!sigla.equals(other.sigla))
return false;
return true;
}
@Override
public String toString() {
return "Uf [id=" + id + ", codigo=" + codigo + ", sigla=" + sigla
+ ", nome=" + nome + "]";
}
}
Classe Cidade
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "CIDADE")
@SequenceGenerator(name = "CIDADE_ID_SEQ", sequenceName = "CIDADE_ID_SEQ", allocationSize = 1, initialValue = 0)
public class Cidade {
private static final long serialVersionUID = 1L;
// Atributos da classe
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CIDADE_ID_SEQ")
@Column(name = "ID", nullable = false)
private long id;
@Column(name="IBGE")
private String ibge;
@Column(name="CODIGO")
private String codigo;
@Column(name="NOME")
private String nome;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="IDUF")
private Uf uf;
public Cidade() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getIbge() {
return ibge;
}
public void setIbge(String ibge) {
this.ibge = ibge;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Uf getUf() {
return uf;
}
public void setUf(Uf uf) {
this.uf = uf;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
result = prime * result + ((ibge == null) ? 0 : ibge.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + ((uf == null) ? 0 : uf.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Cidade))
return false;
Cidade other = (Cidade) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
if (ibge == null) {
if (other.ibge != null)
return false;
} else if (!ibge.equals(other.ibge))
return false;
if (id != other.id)
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (uf == null) {
if (other.uf != null)
return false;
} else if (!uf.equals(other.uf))
return false;
return true;
}
@Override
public String toString() {
return "Cidade [id=" + id + ", ibge=" + ibge + ", codigo=" + codigo
+ ", nome=" + nome + ", uf=" + uf + "]";
}
}
Controlador
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.swing.JOptionPane;
import org.hibernate.bytecode.buildtime.Logger;
import br.com.freedom.controlador.ConexaoDB;
import br.com.freedom.modelo.localizacao.Cidade;
public class CidadeControlador {
EntityManagerFactory emf = null;
EntityManager em = null;
protected Logger log;
public CidadeControlador() {
// TODO Auto-generated constructor stub
}
public void salvar(Cidade object) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = ConexaoDB.getInstancia();
em = emf.createEntityManager();
em.getTransaction().begin();
// Salva os dados da .
em.persist(object);
// Finaliza a transação.
em.getTransaction().commit();
System.out.println("Salvando...");
} catch (Exception ex) {
if (em != null && em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
log.error("Erro ao salvar");
} finally {
if (em != null) {
em.clear();
em.close();
emf.close();
}
}
}
}
Classe que chama o controlador para salvar objeto
[code]
public class ProgramUfTest {
public static void main(String[] args) {
Uf uf=null;
UfControlador controlador = new UfControlador();
uf = controlador.getUf(1);
CidadeControlador cidade_con = new CidadeControlador();
Cidade c = new Cidade();
c.setCodigo("Abc");
c.setIbge("123");
c.setNome("Peixoto de azevedo");
c.setUf(uf);
System.out.println(c.getUf().getId());
cidade_con.salvar(c);
System.out.println(uf.toString());
}
}[/code]
erro emitido
3275 [main] INFO org.hibernate.tool.hbm2ddl.SchemaUpdate - schema update complete
Hibernate:
select
nextval ('CIDADE_ID_SEQ')
Hibernate:
insert
into
CIDADE
(CODIGO, IBGE, NOME, IDUF, ID)
values
(?, ?, ?, ?, ?)
3361 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: 23503
3361 [main] ERROR org.hibernate.util.JDBCExceptionReporter - ERRO: inserção ou atualização em tabela "cidade" viola restrição de chave estrangeira "fk_cidade_to_uf"
Detalhe: Chave (id)=(8) não está presente na tabela "uf".
3369 [main] INFO org.hibernate.impl.SessionFactoryImpl - closing
3369 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - cleaning up connection pool: jdbc:postgresql://127.0.0.1:5432/freedom?autoReconnect=true
Exception in thread "main" java.lang.NullPointerException
at br.com.freedom.controlador.localizacao.CidadeControlador.salvar(CidadeControlador.java:39)
at br.com.freedom.controlador.test.ProgramUfTest.main(ProgramUfTest.java:21)