Bom Dia Pessoal.
Já tentei de todos as formas mapear um relacionamento Pedido-Itens.
Não funciona na inclusão, porém, nas consultas e atualizações sem problema.
Não consegui identificar o que está errado. Segue o codigo abaixo:
Classe Pedidos:
public class Pedidos implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "cliente", nullable = false)
private String cliente;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idPedido")
private Collection<Itens> itensCollection;
// Construtor, getters e setters...
}
Classe Itens:
public class Itens implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "item", nullable = false)
private String item;
@JoinColumn(name = "id_pedido", referencedColumnName = "id")
@ManyToOne
private Pedidos idPedido;
// Construtor, getters e setters...
}
Classe de teste:
public class Main {
/** Creates a new instance of Main */
public Main() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("TesteJPAPU");
EntityManager em = factory.createEntityManager();
ArrayList<Itens> itens = new ArrayList<Itens>();
Itens item1 = new Itens();
item1.setItem("Item1");
itens.add(item1);
Itens item2 = new Itens();
item2.setItem("Item2");
itens.add(item2);
Pedidos pedido = new Pedidos();
pedido.setCliente("Cliente1");
pedido.setItensCollection(itens);
//...
em.getTransaction().begin();
em.persist(pedido);
em.getTransaction().commit();
}
public static void main(String[] args) {
// TODO code application logic here
new Main();
}
}
Script do Banco de dados MySql:
CREATE TABLE `test`.`pedidos` (
`id` int(10) unsigned NOT NULL auto_increment,
`cliente` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `test`.`itens` (
`id` int(10) unsigned NOT NULL auto_increment,
`id_pedido` int(10) unsigned NOT NULL,
`item` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_itens_1` (`id_pedido`),
CONSTRAINT `FK_itens_1` FOREIGN KEY (`id_pedido`) REFERENCES `pedidos` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Parte da exception lançada:
Exception in thread "main" javax.persistence.RollbackException: Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id_pedido' cannot be nullError Code: 1048
Call:INSERT INTO itens (item, id_pedido) VALUES (?, ?)
bind => [Item1, null]
Query:InsertObjectQuery(testejpa.pojos.Itens[id=null])
Se alguem puder me ajudar? Agradeço…