Pessoal tenho a classe abaixo de pedidos onde existe um relacionamento entre 3 bancos.
Pedidos
Clientes
Estoque
o banco pedidos recebe uma chave estrangeira de cliente(id) e tbm do estoque ( idproduto).
Segue minha classe:
@Entity
@Table(name = "pedidos")
@NamedQueries({
@NamedQuery(name = "Pedidos.findAll", query = "SELECT p FROM Pedidos p"),
@NamedQuery(name = "Pedidos.findByIdPedidos", query = "SELECT p FROM Pedidos p WHERE p.idPedidos = :idPedidos"),
@NamedQuery(name = "Pedidos.findByCliente", query = "SELECT p FROM Pedidos p WHERE p.cliente = :cliente"),
@NamedQuery(name = "Pedidos.findByProduto", query = "SELECT p FROM Pedidos p WHERE p.produto = :produto"),
@NamedQuery(name = "Pedidos.findByQnt", query = "SELECT p FROM Pedidos p WHERE p.qnt = :qnt"),
@NamedQuery(name = "Pedidos.findByValor", query = "SELECT p FROM Pedidos p WHERE p.valor = :valor"),
@NamedQuery(name = "Pedidos.findByData", query = "SELECT p FROM Pedidos p WHERE p.data = :data"),
@NamedQuery(name = "Pedidos.findByStatus", query = "SELECT p FROM Pedidos p WHERE p.status = :status"),
@NamedQuery(name = "Pedidos.findByPago", query = "SELECT p FROM Pedidos p WHERE p.pago = :pago")})
public class Pedidos implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "IdPedidos")
private Integer idPedidos;
@Basic(optional = false)
@Column(name = "Cliente")
private String cliente;
@Basic(optional = false)
@Column(name = "Produto")
private String produto;
@Basic(optional = false)
@Column(name = "Qnt")
private int qnt;
@Basic(optional = false)
@Column(name = "Valor")
private float valor;
@Basic(optional = false)
@Column(name = "Data")
private String data;
@Basic(optional = false)
@Column(name = "Status")
private String status;
@Basic(optional = false)
@Column(name = "Pago")
private String pago;
@JoinColumn(name = "idCliente", referencedColumnName = "IdCliente")
@ManyToOne(optional = false)
private Clientes clientes;
@JoinColumn(name = "idProduto", referencedColumnName = "code")
@ManyToOne(optional = false)
private Estoque estoque;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pedidos")
private Collection<Recebimento> recebimentoCollection;
public Pedidos() {
}
public Pedidos(Integer idPedidos) {
this.idPedidos = idPedidos;
}
public Pedidos(Integer idPedidos, String cliente, String produto, int qnt, float valor, String data, String status, String pago) {
this.idPedidos = idPedidos;
this.cliente = cliente;
this.produto = produto;
this.qnt = qnt;
this.valor = valor;
this.data = data;
this.status = status;
this.pago = pago;
}
public Integer getIdPedidos() {
return idPedidos;
}
public void setIdPedidos(Integer idPedidos) {
this.idPedidos = idPedidos;
}
public String getCliente() {
return cliente;
}
public void setCliente(String cliente) {
this.cliente = cliente;
}
public String getProduto() {
return produto;
}
public void setProduto(String produto) {
this.produto = produto;
}
public int getQnt() {
return qnt;
}
public void setQnt(int qnt) {
this.qnt = qnt;
}
public float getValor() {
return valor;
}
public void setValor(float valor) {
this.valor = valor;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPago() {
return pago;
}
public void setPago(String pago) {
this.pago = pago;
}
public Clientes getClientes() {
return clientes;
}
public void setClientes(Clientes clientes) {
this.clientes = clientes;
}
public Estoque getEstoque() {
return estoque;
}
public void setEstoque(Estoque estoque) {
this.estoque = estoque;
}
public Collection<Recebimento> getRecebimentoCollection() {
return recebimentoCollection;
}
public void setRecebimentoCollection(Collection<Recebimento> recebimentoCollection) {
this.recebimentoCollection = recebimentoCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idPedidos != null ? idPedidos.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Pedidos)) {
return false;
}
Pedidos other = (Pedidos) object;
if ((this.idPedidos == null && other.idPedidos != null) || (this.idPedidos != null && !this.idPedidos.equals(other.idPedidos))) {
return false;
}
return true;
}
@Override
public String toString() {
return "sistema.Objetos.Pedidos[idPedidos=" + idPedidos + "]";
}
}
Crei um um Controlador JPA para essa classe:
public class PedidosJpaController {
public PedidosJpaController() {
emf = Persistence.createEntityManagerFactory("SistemaPU");
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Pedidos pedidos) {
if (pedidos.getRecebimentoCollection() == null) {
pedidos.setRecebimentoCollection(new ArrayList<Recebimento>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Clientes clientes = pedidos.getClientes();
if (clientes != null) {
clientes = em.getReference(clientes.getClass(), clientes.getIdCliente());
pedidos.setClientes(clientes);
}
Estoque estoque = pedidos.getEstoque();
if (estoque != null) {
estoque = em.getReference(estoque.getClass(), estoque.getCode());
pedidos.setEstoque(estoque);
}
Collection<Recebimento> attachedRecebimentoCollection = new ArrayList<Recebimento>();
for (Recebimento recebimentoCollectionRecebimentoToAttach : pedidos.getRecebimentoCollection()) {
recebimentoCollectionRecebimentoToAttach = em.getReference(recebimentoCollectionRecebimentoToAttach.getClass(), recebimentoCollectionRecebimentoToAttach.getIdPagamento());
attachedRecebimentoCollection.add(recebimentoCollectionRecebimentoToAttach);
}
pedidos.setRecebimentoCollection(attachedRecebimentoCollection);
em.persist(pedidos);
if (clientes != null) {
clientes.getPedidosCollection().add(pedidos);
clientes = em.merge(clientes);
}
if (estoque != null) {
estoque.getPedidosCollection().add(pedidos);
estoque = em.merge(estoque);
}
for (Recebimento recebimentoCollectionRecebimento : pedidos.getRecebimentoCollection()) {
Pedidos oldPedidosOfRecebimentoCollectionRecebimento = recebimentoCollectionRecebimento.getPedidos();
recebimentoCollectionRecebimento.setPedidos(pedidos);
recebimentoCollectionRecebimento = em.merge(recebimentoCollectionRecebimento);
if (oldPedidosOfRecebimentoCollectionRecebimento != null) {
oldPedidosOfRecebimentoCollectionRecebimento.getRecebimentoCollection().remove(recebimentoCollectionRecebimento);
oldPedidosOfRecebimentoCollectionRecebimento = em.merge(oldPedidosOfRecebimentoCollectionRecebimento);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Pedidos pedidos) throws IllegalOrphanException, NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Pedidos persistentPedidos = em.find(Pedidos.class, pedidos.getIdPedidos());
Clientes clientesOld = persistentPedidos.getClientes();
Clientes clientesNew = pedidos.getClientes();
Estoque estoqueOld = persistentPedidos.getEstoque();
Estoque estoqueNew = pedidos.getEstoque();
Collection<Recebimento> recebimentoCollectionOld = persistentPedidos.getRecebimentoCollection();
Collection<Recebimento> recebimentoCollectionNew = pedidos.getRecebimentoCollection();
List<String> illegalOrphanMessages = null;
for (Recebimento recebimentoCollectionOldRecebimento : recebimentoCollectionOld) {
if (!recebimentoCollectionNew.contains(recebimentoCollectionOldRecebimento)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain Recebimento " + recebimentoCollectionOldRecebimento + " since its pedidos field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
if (clientesNew != null) {
clientesNew = em.getReference(clientesNew.getClass(), clientesNew.getIdCliente());
pedidos.setClientes(clientesNew);
}
if (estoqueNew != null) {
estoqueNew = em.getReference(estoqueNew.getClass(), estoqueNew.getCode());
pedidos.setEstoque(estoqueNew);
}
Collection<Recebimento> attachedRecebimentoCollectionNew = new ArrayList<Recebimento>();
for (Recebimento recebimentoCollectionNewRecebimentoToAttach : recebimentoCollectionNew) {
recebimentoCollectionNewRecebimentoToAttach = em.getReference(recebimentoCollectionNewRecebimentoToAttach.getClass(), recebimentoCollectionNewRecebimentoToAttach.getIdPagamento());
attachedRecebimentoCollectionNew.add(recebimentoCollectionNewRecebimentoToAttach);
}
recebimentoCollectionNew = attachedRecebimentoCollectionNew;
pedidos.setRecebimentoCollection(recebimentoCollectionNew);
pedidos = em.merge(pedidos);
if (clientesOld != null && !clientesOld.equals(clientesNew)) {
clientesOld.getPedidosCollection().remove(pedidos);
clientesOld = em.merge(clientesOld);
}
if (clientesNew != null && !clientesNew.equals(clientesOld)) {
clientesNew.getPedidosCollection().add(pedidos);
clientesNew = em.merge(clientesNew);
}
if (estoqueOld != null && !estoqueOld.equals(estoqueNew)) {
estoqueOld.getPedidosCollection().remove(pedidos);
estoqueOld = em.merge(estoqueOld);
}
if (estoqueNew != null && !estoqueNew.equals(estoqueOld)) {
estoqueNew.getPedidosCollection().add(pedidos);
estoqueNew = em.merge(estoqueNew);
}
for (Recebimento recebimentoCollectionNewRecebimento : recebimentoCollectionNew) {
if (!recebimentoCollectionOld.contains(recebimentoCollectionNewRecebimento)) {
Pedidos oldPedidosOfRecebimentoCollectionNewRecebimento = recebimentoCollectionNewRecebimento.getPedidos();
recebimentoCollectionNewRecebimento.setPedidos(pedidos);
recebimentoCollectionNewRecebimento = em.merge(recebimentoCollectionNewRecebimento);
if (oldPedidosOfRecebimentoCollectionNewRecebimento != null && !oldPedidosOfRecebimentoCollectionNewRecebimento.equals(pedidos)) {
oldPedidosOfRecebimentoCollectionNewRecebimento.getRecebimentoCollection().remove(recebimentoCollectionNewRecebimento);
oldPedidosOfRecebimentoCollectionNewRecebimento = em.merge(oldPedidosOfRecebimentoCollectionNewRecebimento);
}
}
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = pedidos.getIdPedidos();
if (findPedidos(id) == null) {
throw new NonexistentEntityException("The pedidos with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Pedidos pedidos;
try {
pedidos = em.getReference(Pedidos.class, id);
pedidos.getIdPedidos();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The pedidos with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
Collection<Recebimento> recebimentoCollectionOrphanCheck = pedidos.getRecebimentoCollection();
for (Recebimento recebimentoCollectionOrphanCheckRecebimento : recebimentoCollectionOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Pedidos (" + pedidos + ") cannot be destroyed since the Recebimento " + recebimentoCollectionOrphanCheckRecebimento + " in its recebimentoCollection field has a non-nullable pedidos field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
Clientes clientes = pedidos.getClientes();
if (clientes != null) {
clientes.getPedidosCollection().remove(pedidos);
clientes = em.merge(clientes);
}
Estoque estoque = pedidos.getEstoque();
if (estoque != null) {
estoque.getPedidosCollection().remove(pedidos);
estoque = em.merge(estoque);
}
em.remove(pedidos);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Pedidos> findPedidosEntities() {
return findPedidosEntities(true, -1, -1);
}
public List<Pedidos> findPedidosEntities(int maxResults, int firstResult) {
return findPedidosEntities(false, maxResults, firstResult);
}
private List<Pedidos> findPedidosEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Pedidos.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Pedidos findPedidos(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Pedidos.class, id);
} finally {
em.close();
}
}
public int getPedidosCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Pedidos> rt = cq.from(Pedidos.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
public List<Pedidos> consultaPedido(String txt){
EntityManager em = getEntityManager();
Query q = em.createNamedQuery("Pedidos.findByCliente");
q.setParameter("cliente","%" + txt + "%");
return (List<Pedidos>) q.getResultList();
}
}
O problema que estou apenas listando esses meus dados e está retornando o erro abaixo:
Listar dados:
public void listarPedidos() throws SQLException{
PedidosJpaController tmp = new PedidosJpaController();
model = new PedidosTableModel(tmp.findPedidosEntities());
jTable1.setModel(model);
Erro:
run:
Exception in thread "AWT-EventQueue-0" Local Exception Stack:
Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [SistemaPU] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class sistema.Objetos.Estoque] uses a non-entity [class sistema.Objetos.Recebimento] as target entity in the relationship attribute [field recebimentoCollection].
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:126)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:133)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:65)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at sistema.JPA.PedidosJpaController.<init>(PedidosJpaController.java:32)
at sistema.FramePedidos.listarPedidos(FramePedidos.java:573)
at sistema.FramePedidos.<init>(FramePedidos.java:37)
at sistema.SistemaHome.visualizarPedidos(SistemaHome.java:448)
at sistema.SistemaHome.BT_PedidosActionPerformed(SistemaHome.java:354)
at sistema.SistemaHome.access$1200(SistemaHome.java:25)
at sistema.SistemaHome$8.actionPerformed(SistemaHome.java:172)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6267)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [SistemaPU] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class sistema.Objetos.Estoque] uses a non-entity [class sistema.Objetos.Recebimento] as target entity in the relationship attribute [field recebimentoCollection].
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:991)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.callPredeploy(JPAInitializer.java:88)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:124)
... 35 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [SistemaPU] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class sistema.Objetos.Estoque] uses a non-entity [class sistema.Objetos.Recebimento] as target entity in the relationship attribute [field recebimentoCollection].
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:210)
... 38 more
Caused by: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class sistema.Objetos.Estoque] uses a non-entity [class sistema.Objetos.Recebimento] as target entity in the relationship attribute [field recebimentoCollection].
at org.eclipse.persistence.exceptions.ValidationException.nonEntityTargetInRelationship(ValidationException.java:1320)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.RelationshipAccessor.getReferenceDescriptor(RelationshipAccessor.java:329)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.RelationshipAccessor.getOwningMapping(RelationshipAccessor.java:292)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.OneToManyAccessor.processOneToManyMapping(OneToManyAccessor.java:168)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.OneToManyAccessor.process(OneToManyAccessor.java:111)
at org.eclipse.persistence.internal.jpa.metadata.accessors.mappings.RelationshipAccessor.processRelationship(RelationshipAccessor.java:546)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processRelationshipAccessors(MetadataProject.java:1085)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processStage3(MetadataProject.java:1364)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.processORMMetadata(MetadataProcessor.java:462)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:390)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:945)
... 37 more
CONSTRUÍDO COM SUCESSO (tempo total: 8 segundos)