Pessoal,
Tenho duas tabelas: TiposItens e Itens.
O relacionamento delas é: TiposItens 1…* Itens
Estou testando a inserção de um item utilizando a classe BigTeste (Um pequeno teste para ver se minhas entidades estão persistindo corretamente).
Ele insere normalmente, porém o campo tipoItemID fica nulo.
O registro TipoItens que estou utilizando existe, pois se der um toString() no objeto tipoItemID, ele não me retorna nulo…
Alguém consegue me dar uma luz ? Espero ter sido claro na minha dúvida…
Valeu!
Segue o sql das tabelas e as classes.
CREATE TABLE IF NOT EXISTS `TiposItens` (
`id` INT NOT NULL AUTO_INCREMENT ,
`descricao` VARCHAR(45) NOT NULL ,
`status` VARCHAR(1) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `Itens` (
`id` INT NOT NULL AUTO_INCREMENT ,
`tipoItemID` INT NOT NULL ,
`descricao` VARCHAR(45) NOT NULL ,
`qtde` FLOAT NULL DEFAULT NULL ,
`qtdeMin` FLOAT NULL DEFAULT NULL ,
`preco` FLOAT NULL DEFAULT NULL ,
`status` VARCHAR(1) NOT NULL ,
`um` VARCHAR(3) NOT NULL ,
PRIMARY KEY (`id`) ,
CONSTRAINT `Item_fk1`
FOREIGN KEY (`tipoItemID` )
REFERENCES `mydb`.`TiposItens` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
BigTeste
package br.com.scrapsolution.testes;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import br.com.scrapsolution.tables.Itens;
import br.com.scrapsolution.tables.TiposItens;
public class BigTeste implements Serializable {
private static final long serialVersionUID = 1L;
private static EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;
private static EntityTransaction entityTransaction;
public static void main(String[] args) {
// TODO Auto-generated method stub
entityManagerFactory = Persistence.createEntityManagerFactory("scrapSolution");
entityManager = entityManagerFactory.createEntityManager();
entityTransaction = entityManager.getTransaction();
runCriacoes();
runListas();
}
@SuppressWarnings({ "unchecked", "cast" })
public static void runListas(){
System.out.println("------------------------------------------TIPOS ITENS------------------------------------------");
List<TiposItens> tpItens = (List<TiposItens>) entityManager.createQuery("from br.com.scrapsolution.tables.TiposItens where status <> 'D'").getResultList();
for (Iterator iterator = tpItens.iterator(); iterator.hasNext();) {
TiposItens tpItensIterator = (TiposItens) iterator.next();
System.out.println(tpItensIterator.toString());
}
System.out.println("------------------------------------------ITENS------------------------------------------------");
List<Itens> itens = (List<Itens>) entityManager.createQuery("from br.com.scrapsolution.tables.Itens").getResultList();
for (Iterator iterator = itens.iterator(); iterator.hasNext();) {
Itens itensIterator = (Itens) iterator.next();
System.out.println(itensIterator.toString());
}
System.out.println("---------------------------------------Fornecedores---------------------------------------");
}
public static void runCommit(Object obj){
try {
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
entityManager.persist(obj);
entityManager.flush();
entityTransaction.commit();
} catch (Exception exc) {
entityTransaction.rollback();
exc.printStackTrace();
}
}
public static void runCriacoes(){
TiposItens tpItens = (TiposItens) entityManager.createQuery("from br.com.scrapsolution.tables.TiposItens where id = 1").getSingleResult();
Itens item = new Itens("Teste",15F,"UN",10F,2.5F,"A",tpItens);
runCommit(item);
}
}
Classe Itens
package br.com.scrapsolution.tables;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
@Entity
@Table (name="Itens")
public class Itens implements Serializable {
private static final long serialVersionUID = 1L;
public Itens() {
//super();
}
public Itens(String descricao, Float qtde, String um, Float qtdeMin,
Float preco, String status, TiposItens tipoItem) {
super();
this.descricao = descricao;
this.qtde = qtde;
this.um = um;
this.qtdeMin = qtdeMin;
this.preco = preco;
this.status = status;
this.tipoItemID = tipoItem;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column (name="descricao")
private String descricao;
@Column (name="qtde")
private Float qtde;
@Column (name="um")
private String um;
@Column (name="qtdeMin")
private Float qtdeMin;
@Column (name="preco")
private Float preco;
@Column(name="status")
private String status;
//Essa parte eu mudei varias vezes para tentar resolver, mas nada!!
@ManyToOne (optional = false, fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@JoinColumn (name="tipoItemID", referencedColumnName="id" , insertable=false, updatable=false, nullable=false)
private TiposItens tipoItemID;
@OneToMany (mappedBy="item", fetch = FetchType.EAGER)
private Set<PedComItens> pedComItens;
//Getters
public Long getId() { return id; }
public String getDescricao() { return descricao; }
public Float getQtde() { return qtde; }
public Float getQtdeMin() { return qtdeMin; }
public Float getPreco() { return preco; }
public TiposItens getTipoItem() { return tipoItemID; }
public String getStatus() { return status; }
public Set<PedComItens> getPedComItens() { return pedComItens; }
public String getUm() { return um; }
//Setters
public void setId(Long id) { this.id = id; }
public void setDescricao(String descricao) { this.descricao = descricao; }
public void setQtde(Float qtde) { this.qtde = qtde; }
public void setQtdeMin(Float qtdeMin) { this.qtdeMin = qtdeMin; }
public void setPreco(Float precoItem) { this.preco = precoItem; }
public void setTipoItem(TiposItens tipoItem) { this.tipoItemID = tipoItem; }
public void setStatus(String status) { this.status = status; }
public void setPedComItens(Set<PedComItens> pedComItens) { this.pedComItens = pedComItens; }
public void setUm(String um) { this.um = um; }
@Override
public String toString(){
return getId() + " - " +
getDescricao() +
(((tipoItemID) == null) ? "" : (" - " + this.tipoItemID.getDescricao()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((pedComItens == null) ? 0 : pedComItens.hashCode());
result = prime * result + ((preco == null) ? 0 : preco.hashCode());
result = prime * result + ((qtde == null) ? 0 : qtde.hashCode());
result = prime * result + ((qtdeMin == null) ? 0 : qtdeMin.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result
+ ((tipoItemID == null) ? 0 : tipoItemID.hashCode());
result = prime * result + ((um == null) ? 0 : um.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;
Itens other = (Itens) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (pedComItens == null) {
if (other.pedComItens != null)
return false;
} else if (!pedComItens.equals(other.pedComItens))
return false;
if (preco == null) {
if (other.preco != null)
return false;
} else if (!preco.equals(other.preco))
return false;
if (qtde == null) {
if (other.qtde != null)
return false;
} else if (!qtde.equals(other.qtde))
return false;
if (qtdeMin == null) {
if (other.qtdeMin != null)
return false;
} else if (!qtdeMin.equals(other.qtdeMin))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (tipoItemID == null) {
if (other.tipoItemID != null)
return false;
} else if (!tipoItemID.equals(other.tipoItemID))
return false;
if (um == null) {
if (other.um != null)
return false;
} else if (!um.equals(other.um))
return false;
return true;
}
}
[b]Classe TiposItens[/b]
package br.com.scrapsolution.tables;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
@Entity
@Table (name="TiposItens")
public class TiposItens implements Serializable {
private static final long serialVersionUID = 1L;
public TiposItens() {
//super();
}
public TiposItens(String descricao) {
super();
this.descricao = descricao;
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", nullable=false)
private Long id;
@Column
private String descricao;
@Column(name="status")
private String status;
@OneToMany (mappedBy="tipoItemID", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinColumn (name="tipoItemID")
private List<Itens> itens;
public Long getId() { return id; }
public String getDescricao() { return descricao; }
public String getStatus() { return status; }
public List<Itens> getItens() { return itens; }
public void setId(Long id) { this.id = id; }
public void setDescricao(String descricao) { this.descricao = descricao; }
public void setStatus(String status) { this.status = status; }
public void setItens(List<Itens> itens) { this.itens = itens; }
@Override
public String toString(){
return getId() + " - " + getDescricao();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((status == null) ? 0 : status.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;
TiposItens other = (TiposItens) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
}
Teste Itens