Olá usuários do forum
Estou iniciando com JPA, uso eclipse, mas particularmente estou num projeto (pequeno) com Netbeans. Vi algumas classes do JPA fazerem quase tudo por mim, de modo que até agora nao precisei se quer digitar uma unica linha de sql, tive mais tempo de me procupar com a lógica do nenhum, assim eu e o JPA estávamos no maior amor do mundo, quando de repente ao chamar o método edit (criado automaticamente em um dos controllers que gerei) aparece o seguinte erro:
SEVERE: Você tem um erro de sintaxe no seu SQL próximo a 'as Mapa6_5_1_, anunciocol0_.Site as Site5_1_, anunciocol0_.Visualizacoes as Visu' na linha 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not initialize a collection: [entidades.Cliente.anuncioCollection#7]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.loadCollection(Loader.java:2001)
at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:36)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:565)
at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60)
at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1716)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:344)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:249)
at controladores.CadastroCliente.edit(CadastroCliente.java:110)
at Teste.main(Teste.java:40)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Você tem um erro de sintaxe no seu SQL próximo a 'as Mapa6_5_1_, anunciocol0_.Site as Site5_1_, anunciocol0_.Visualizacoes as Visu' na linha 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2228)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.loadCollection(Loader.java:1994)
... 9 more
Java Result: 1
Vou mandar aqui pelo meno o código das classes envolvidas e também a classe Teste que criei exatamente pra tentar investigar esse erro (que inicialmente eu estava usando em Servlet:
Classe de Entidade: Anuncio
[code]package entidades;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
-
@author Adriano
*/
@Entity
@Table(name = “anuncio”)
@NamedQueries({
@NamedQuery(name = “Anuncio.findAll”, query = “SELECT a FROM Anuncio a”),
@NamedQuery(name = “Anuncio.findByIdAnuncio”, query = “SELECT a FROM Anuncio a WHERE a.idAnuncio = :idAnuncio”),
@NamedQuery(name = “Anuncio.findByEmail”, query = “SELECT a FROM Anuncio a WHERE a.email = :email”),
@NamedQuery(name = “Anuncio.findBySite”, query = “SELECT a FROM Anuncio a WHERE a.site = :site”),
@NamedQuery(name = “Anuncio.findByLocalizacao”, query = “SELECT a FROM Anuncio a WHERE a.localizacao = :localizacao”),
@NamedQuery(name = “Anuncio.findByVisualizacoes”, query = “SELECT a FROM Anuncio a WHERE a.visualizacoes = :visualizacoes”)})
public class Anuncio implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = “idAnuncio”)
private Integer idAnuncio;
@Basic(optional = false)
//@Lob
@Column(name = “Logomarca”)
private byte[] logomarca;
@Column(name = “Email”)
private String email;
@Column(name = “Site”)
private String site;
@Lob
@Column(name = “Descricao”)
private String descricao;
@Lob
@Column(name = “Mapa Google”)
private String mapaGoogle;
@Column(name = “Localizacao”)
private Integer localizacao;
@Column(name = “Visualizacoes”)
private Integer visualizacoes;
@JoinColumn(name = “Categoria_idRamos”, referencedColumnName = “idRamos”)
@ManyToOne(optional = false)
private Categoria categoriaidRamos;
@JoinColumn(name = “Cliente_idCliente”, referencedColumnName = “idCliente”)
@ManyToOne(optional = false)
private Cliente clienteidCliente;public Anuncio() {
}public Anuncio(Integer idAnuncio) {
this.idAnuncio = idAnuncio;
}public Anuncio(Integer idAnuncio, byte[] logomarca) {
this.idAnuncio = idAnuncio;
this.logomarca = logomarca;
}public Integer getIdAnuncio() {
return idAnuncio;
}public void setIdAnuncio(Integer idAnuncio) {
this.idAnuncio = idAnuncio;
}public byte[] getLogomarca() {
return logomarca;
}public void setLogomarca(byte[] logomarca) {
this.logomarca = logomarca;
}public String getEmail() {
return email;
}public void setEmail(String email) {
this.email = email;
}public String getSite() {
return site;
}public void setSite(String site) {
this.site = site;
}public String getDescricao() {
return descricao;
}public void setDescricao(String descricao) {
this.descricao = descricao;
}public String getMapaGoogle() {
return mapaGoogle;
}public void setMapaGoogle(String mapaGoogle) {
this.mapaGoogle = mapaGoogle;
}public Integer getLocalizacao() {
return localizacao;
}public void setLocalizacao(Integer localizacao) {
this.localizacao = localizacao;
}public Integer getVisualizacoes() {
return visualizacoes;
}public void setVisualizacoes(Integer visualizacoes) {
this.visualizacoes = visualizacoes;
}public Categoria getCategoriaidRamos() {
return categoriaidRamos;
}public void setCategoriaidRamos(Categoria categoriaidRamos) {
this.categoriaidRamos = categoriaidRamos;
}public Cliente getClienteidCliente() {
return clienteidCliente;
}public void setClienteidCliente(Cliente clienteidCliente) {
this.clienteidCliente = clienteidCliente;
}@Override
public int hashCode() {
int hash = 0;
hash += (idAnuncio != null ? idAnuncio.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 Anuncio)) {
return false;
}
Anuncio other = (Anuncio) object;
if ((this.idAnuncio == null && other.idAnuncio != null) || (this.idAnuncio != null && !this.idAnuncio.equals(other.idAnuncio))) {
return false;
}
return true;
}@Override
public String toString() {
return “entidades.Anuncio[idAnuncio=” + idAnuncio + “]”;
}
}[/code]
Classe de Entidade: Cliente
[code]package entidades;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
-
@author Adriano
*/
@Entity
@Table(name = “cliente”)
@NamedQueries({
@NamedQuery(name = “Cliente.findAll”, query = “SELECT c FROM Cliente c”),
@NamedQuery(name = “Cliente.findByIdCliente”, query = “SELECT c FROM Cliente c WHERE c.idCliente = :idCliente”),
@NamedQuery(name = “Cliente.findByDataCadastro”, query = “SELECT c FROM Cliente c WHERE c.dataCadastro = :dataCadastro”),
@NamedQuery(name = “Cliente.findByNome”, query = “SELECT c FROM Cliente c WHERE c.nome = :nome”),
@NamedQuery(name = “Cliente.findByResponsavel”, query = “SELECT c FROM Cliente c WHERE c.responsavel = :responsavel”),
@NamedQuery(name = “Cliente.findByCpfCnpj”, query = “SELECT c FROM Cliente c WHERE c.cpfCnpj = :cpfCnpj”),
@NamedQuery(name = “Cliente.findByEndereco”, query = “SELECT c FROM Cliente c WHERE c.endereco = :endereco”),
@NamedQuery(name = “Cliente.findByBairro”, query = “SELECT c FROM Cliente c WHERE c.bairro = :bairro”),
@NamedQuery(name = “Cliente.findByCep”, query = “SELECT c FROM Cliente c WHERE c.cep = :cep”),
@NamedQuery(name = “Cliente.findByCidade”, query = “SELECT c FROM Cliente c WHERE c.cidade = :cidade”),
@NamedQuery(name = “Cliente.findByEstado”, query = “SELECT c FROM Cliente c WHERE c.estado = :estado”),
@NamedQuery(name = “Cliente.findByTelefoneFixo”, query = “SELECT c FROM Cliente c WHERE c.telefoneFixo = :telefoneFixo”),
@NamedQuery(name = “Cliente.findByFax”, query = “SELECT c FROM Cliente c WHERE c.fax = :fax”),
@NamedQuery(name = “Cliente.findByCelular”, query = “SELECT c FROM Cliente c WHERE c.celular = :celular”),
@NamedQuery(name = “Cliente.findBySite”, query = “SELECT c FROM Cliente c WHERE c.site = :site”),
@NamedQuery(name = “Cliente.findByEmail”, query = “SELECT c FROM Cliente c WHERE c.email = :email”)})
public class Cliente implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = “idCliente”)
private Integer idCliente;
@Column(name = “DataCadastro”)
@Temporal(TemporalType.DATE)
private Date dataCadastro;
@Column(name = “Nome”)
private String nome;
@Column(name = “Responsavel”)
private String responsavel;
@Column(name = “CpfCnpj”)
private String cpfCnpj;
@Column(name = “Endereco”)
private String endereco;
@Column(name = “Bairro”)
private String bairro;
@Column(name = “Cep”)
private String cep;
@Column(name = “Cidade”)
private String cidade;
@Column(name = “Estado”)
private String estado;
@Column(name = “TelefoneFixo”)
private String telefoneFixo;
@Column(name = “Fax”)
private String fax;
@Column(name = “Celular”)
private String celular;
@Column(name = “Site”)
private String site;
@Column(name = “Email”)
private String email;
@OneToMany(cascade = CascadeType.ALL, mappedBy = “clienteidCliente”)
private Collection anuncioCollection;
@JoinColumn(name = “TipoCliente_idTipoCliente”, referencedColumnName = “idTipoCliente”)
@ManyToOne(optional = false)
private TipoCliente tipoClienteidTipoCliente;
@OneToMany(cascade = CascadeType.ALL, mappedBy = “clienteidCliente”)
private Collection usuarioCollection;public Cliente() {
}public Cliente(Integer idCliente) {
this.idCliente = idCliente;
}public Integer getIdCliente() {
return idCliente;
}public void setIdCliente(Integer idCliente) {
this.idCliente = idCliente;
}public Date getDataCadastro() {
return dataCadastro;
}public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}public String getNome() {
return nome;
}public void setNome(String nome) {
this.nome = nome;
}public String getResponsavel() {
return responsavel;
}public void setResponsavel(String responsavel) {
this.responsavel = responsavel;
}public String getCpfCnpj() {
return cpfCnpj;
}public void setCpfCnpj(String cpfCnpj) {
this.cpfCnpj = cpfCnpj;
}public String getEndereco() {
return endereco;
}public void setEndereco(String endereco) {
this.endereco = endereco;
}public String getBairro() {
return bairro;
}public void setBairro(String bairro) {
this.bairro = bairro;
}public String getCep() {
return cep;
}public void setCep(String cep) {
this.cep = cep;
}public String getCidade() {
return cidade;
}public void setCidade(String cidade) {
this.cidade = cidade;
}public String getEstado() {
return estado;
}public void setEstado(String estado) {
this.estado = estado;
}public String getTelefoneFixo() {
return telefoneFixo;
}public void setTelefoneFixo(String telefoneFixo) {
this.telefoneFixo = telefoneFixo;
}public String getFax() {
return fax;
}public void setFax(String fax) {
this.fax = fax;
}public String getCelular() {
return celular;
}public void setCelular(String celular) {
this.celular = celular;
}public String getSite() {
return site;
}public void setSite(String site) {
this.site = site;
}public String getEmail() {
return email;
}public void setEmail(String email) {
this.email = email;
}public Collection getAnuncioCollection() {
return anuncioCollection;
}public void setAnuncioCollection(Collection anuncioCollection) {
this.anuncioCollection = anuncioCollection;
}public TipoCliente getTipoClienteidTipoCliente() {
return tipoClienteidTipoCliente;
}public void setTipoClienteidTipoCliente(TipoCliente tipoClienteidTipoCliente) {
this.tipoClienteidTipoCliente = tipoClienteidTipoCliente;
}public Collection getUsuarioCollection() {
return usuarioCollection;
}public void setUsuarioCollection(Collection usuarioCollection) {
this.usuarioCollection = usuarioCollection;
}@Override
public int hashCode() {
int hash = 0;
hash += (idCliente != null ? idCliente.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 Cliente)) {
return false;
}
Cliente other = (Cliente) object;
if ((this.idCliente == null && other.idCliente != null) || (this.idCliente != null && !this.idCliente.equals(other.idCliente))) {
return false;
}
return true;
}@Override
public String toString() {
return “entidades.Cliente[idCliente=” + idCliente + “]”;
}
}[/code]
CLIENTE TEM UM RELACIONAMENTO DE 1 PARA MUITOS COM ANUNCIOS
Controlador de Anuncio:
[code]package controladores;
import controladores.exceptions.NonexistentEntityException;
import entidades.Anuncio;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidades.Categoria;
import entidades.Cliente;
/**
*
-
@author Adriano
*/
public class CadastroAnuncio {public CadastroAnuncio() {
emf = Persistence.createEntityManagerFactory(“CGPU”);
}
private EntityManagerFactory emf = null;public EntityManager getEntityManager() {
return emf.createEntityManager();
}public void create(Anuncio anuncio) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Categoria categoriaidRamos = anuncio.getCategoriaidRamos();
if (categoriaidRamos != null) {
categoriaidRamos = em.getReference(categoriaidRamos.getClass(), categoriaidRamos.getIdRamos());
anuncio.setCategoriaidRamos(categoriaidRamos);
}
Cliente clienteidCliente = anuncio.getClienteidCliente();
if (clienteidCliente != null) {
clienteidCliente = em.getReference(clienteidCliente.getClass(), clienteidCliente.getIdCliente());
anuncio.setClienteidCliente(clienteidCliente);
}
em.persist(anuncio);
if (categoriaidRamos != null) {
categoriaidRamos.getAnuncioCollection().add(anuncio);
categoriaidRamos = em.merge(categoriaidRamos);
}
if (clienteidCliente != null) {
clienteidCliente.getAnuncioCollection().add(anuncio);
clienteidCliente = em.merge(clienteidCliente);
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}public void edit(Anuncio anuncio) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Anuncio persistentAnuncio = em.find(Anuncio.class, anuncio.getIdAnuncio());
Categoria categoriaidRamosOld = persistentAnuncio.getCategoriaidRamos();
Categoria categoriaidRamosNew = anuncio.getCategoriaidRamos();
Cliente clienteidClienteOld = persistentAnuncio.getClienteidCliente();
Cliente clienteidClienteNew = anuncio.getClienteidCliente();
if (categoriaidRamosNew != null) {
categoriaidRamosNew = em.getReference(categoriaidRamosNew.getClass(), categoriaidRamosNew.getIdRamos());
anuncio.setCategoriaidRamos(categoriaidRamosNew);
}
if (clienteidClienteNew != null) {
clienteidClienteNew = em.getReference(clienteidClienteNew.getClass(), clienteidClienteNew.getIdCliente());
anuncio.setClienteidCliente(clienteidClienteNew);
}
anuncio = em.merge(anuncio);
if (categoriaidRamosOld != null && !categoriaidRamosOld.equals(categoriaidRamosNew)) {
categoriaidRamosOld.getAnuncioCollection().remove(anuncio);
categoriaidRamosOld = em.merge(categoriaidRamosOld);
}
if (categoriaidRamosNew != null && !categoriaidRamosNew.equals(categoriaidRamosOld)) {
categoriaidRamosNew.getAnuncioCollection().add(anuncio);
categoriaidRamosNew = em.merge(categoriaidRamosNew);
}
if (clienteidClienteOld != null && !clienteidClienteOld.equals(clienteidClienteNew)) {
clienteidClienteOld.getAnuncioCollection().remove(anuncio);
clienteidClienteOld = em.merge(clienteidClienteOld);
}
if (clienteidClienteNew != null && !clienteidClienteNew.equals(clienteidClienteOld)) {
clienteidClienteNew.getAnuncioCollection().add(anuncio);
clienteidClienteNew = em.merge(clienteidClienteNew);
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = anuncio.getIdAnuncio();
if (findAnuncio(id) == null) {
throw new NonexistentEntityException(“The anuncio with id " + id + " no longer exists.”);
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}public void destroy(Integer id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Anuncio anuncio;
try {
anuncio = em.getReference(Anuncio.class, id);
anuncio.getIdAnuncio();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException(“The anuncio with id " + id + " no longer exists.”, enfe);
}
Categoria categoriaidRamos = anuncio.getCategoriaidRamos();
if (categoriaidRamos != null) {
categoriaidRamos.getAnuncioCollection().remove(anuncio);
categoriaidRamos = em.merge(categoriaidRamos);
}
Cliente clienteidCliente = anuncio.getClienteidCliente();
if (clienteidCliente != null) {
clienteidCliente.getAnuncioCollection().remove(anuncio);
clienteidCliente = em.merge(clienteidCliente);
}
em.remove(anuncio);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}public List findAnuncioEntities() {
return findAnuncioEntities(true, -1, -1);
}public List findAnuncioEntities(int maxResults, int firstResult) {
return findAnuncioEntities(false, maxResults, firstResult);
}private List findAnuncioEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery(“select object(o) from Anuncio as o”);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}public Anuncio findAnuncio(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Anuncio.class, id);
} finally {
em.close();
}
}public int getAnuncioCount() {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery(“select count(o) from Anuncio as o”);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}[/code]
Controlador de Clientes
[code]package controladores;
import controladores.exceptions.IllegalOrphanException;
import controladores.exceptions.NonexistentEntityException;
import entidades.Cliente;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidades.TipoCliente;
import entidades.Anuncio;
import java.util.ArrayList;
import java.util.Collection;
import entidades.Usuario;
/**
*
-
@author Adriano
*/
public class CadastroCliente {public CadastroCliente() {
emf = Persistence.createEntityManagerFactory(“CGPU”);
}
private EntityManagerFactory emf = null;public EntityManager getEntityManager() {
return emf.createEntityManager();
}public void create(Cliente cliente) {
if (cliente.getAnuncioCollection() == null) {
cliente.setAnuncioCollection(new ArrayList());
}
if (cliente.getUsuarioCollection() == null) {
cliente.setUsuarioCollection(new ArrayList());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
TipoCliente tipoClienteidTipoCliente = cliente.getTipoClienteidTipoCliente();
if (tipoClienteidTipoCliente != null) {
tipoClienteidTipoCliente = em.getReference(tipoClienteidTipoCliente.getClass(), tipoClienteidTipoCliente.getIdTipoCliente());
cliente.setTipoClienteidTipoCliente(tipoClienteidTipoCliente);
}
Collection attachedAnuncioCollection = new ArrayList();
for (Anuncio anuncioCollectionAnuncioToAttach : cliente.getAnuncioCollection()) {
anuncioCollectionAnuncioToAttach = em.getReference(anuncioCollectionAnuncioToAttach.getClass(), anuncioCollectionAnuncioToAttach.getIdAnuncio());
attachedAnuncioCollection.add(anuncioCollectionAnuncioToAttach);
}
cliente.setAnuncioCollection(attachedAnuncioCollection);
Collection attachedUsuarioCollection = new ArrayList();
for (Usuario usuarioCollectionUsuarioToAttach : cliente.getUsuarioCollection()) {
usuarioCollectionUsuarioToAttach = em.getReference(usuarioCollectionUsuarioToAttach.getClass(), usuarioCollectionUsuarioToAttach.getIdUsuario());
attachedUsuarioCollection.add(usuarioCollectionUsuarioToAttach);
}
cliente.setUsuarioCollection(attachedUsuarioCollection);
em.persist(cliente);
if (tipoClienteidTipoCliente != null) {
tipoClienteidTipoCliente.getClienteCollection().add(cliente);
tipoClienteidTipoCliente = em.merge(tipoClienteidTipoCliente);
}
for (Anuncio anuncioCollectionAnuncio : cliente.getAnuncioCollection()) {
Cliente oldClienteidClienteOfAnuncioCollectionAnuncio = anuncioCollectionAnuncio.getClienteidCliente();
anuncioCollectionAnuncio.setClienteidCliente(cliente);
anuncioCollectionAnuncio = em.merge(anuncioCollectionAnuncio);
if (oldClienteidClienteOfAnuncioCollectionAnuncio != null) {
oldClienteidClienteOfAnuncioCollectionAnuncio.getAnuncioCollection().remove(anuncioCollectionAnuncio);
oldClienteidClienteOfAnuncioCollectionAnuncio = em.merge(oldClienteidClienteOfAnuncioCollectionAnuncio);
}
}
for (Usuario usuarioCollectionUsuario : cliente.getUsuarioCollection()) {
Cliente oldClienteidClienteOfUsuarioCollectionUsuario = usuarioCollectionUsuario.getClienteidCliente();
usuarioCollectionUsuario.setClienteidCliente(cliente);
usuarioCollectionUsuario = em.merge(usuarioCollectionUsuario);
if (oldClienteidClienteOfUsuarioCollectionUsuario != null) {
oldClienteidClienteOfUsuarioCollectionUsuario.getUsuarioCollection().remove(usuarioCollectionUsuario);
oldClienteidClienteOfUsuarioCollectionUsuario = em.merge(oldClienteidClienteOfUsuarioCollectionUsuario);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}public void edit(Cliente cliente) throws IllegalOrphanException, NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cliente persistentCliente = em.find(Cliente.class, cliente.getIdCliente());
TipoCliente tipoClienteidTipoClienteOld = persistentCliente.getTipoClienteidTipoCliente();
TipoCliente tipoClienteidTipoClienteNew = cliente.getTipoClienteidTipoCliente();
Collection anuncioCollectionOld = persistentCliente.getAnuncioCollection();
Collection anuncioCollectionNew = cliente.getAnuncioCollection();
Collection usuarioCollectionOld = persistentCliente.getUsuarioCollection();
Collection usuarioCollectionNew = cliente.getUsuarioCollection();
List illegalOrphanMessages = null;
for (Anuncio anuncioCollectionOldAnuncio : anuncioCollectionOld) {
if (!anuncioCollectionNew.contains(anuncioCollectionOldAnuncio)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList();
}
illegalOrphanMessages.add(“You must retain Anuncio " + anuncioCollectionOldAnuncio + " since its clienteidCliente field is not nullable.”);
}
}
for (Usuario usuarioCollectionOldUsuario : usuarioCollectionOld) {
if (!usuarioCollectionNew.contains(usuarioCollectionOldUsuario)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList();
}
illegalOrphanMessages.add(“You must retain Usuario " + usuarioCollectionOldUsuario + " since its clienteidCliente field is not nullable.”);
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
if (tipoClienteidTipoClienteNew != null) {
tipoClienteidTipoClienteNew = em.getReference(tipoClienteidTipoClienteNew.getClass(), tipoClienteidTipoClienteNew.getIdTipoCliente());
cliente.setTipoClienteidTipoCliente(tipoClienteidTipoClienteNew);
}
Collection attachedAnuncioCollectionNew = new ArrayList();
for (Anuncio anuncioCollectionNewAnuncioToAttach : anuncioCollectionNew) {
anuncioCollectionNewAnuncioToAttach = em.getReference(anuncioCollectionNewAnuncioToAttach.getClass(), anuncioCollectionNewAnuncioToAttach.getIdAnuncio());
attachedAnuncioCollectionNew.add(anuncioCollectionNewAnuncioToAttach);
}
anuncioCollectionNew = attachedAnuncioCollectionNew;
cliente.setAnuncioCollection(anuncioCollectionNew);
Collection attachedUsuarioCollectionNew = new ArrayList();
for (Usuario usuarioCollectionNewUsuarioToAttach : usuarioCollectionNew) {
usuarioCollectionNewUsuarioToAttach = em.getReference(usuarioCollectionNewUsuarioToAttach.getClass(), usuarioCollectionNewUsuarioToAttach.getIdUsuario());
attachedUsuarioCollectionNew.add(usuarioCollectionNewUsuarioToAttach);
}
usuarioCollectionNew = attachedUsuarioCollectionNew;
cliente.setUsuarioCollection(usuarioCollectionNew);
cliente = em.merge(cliente);
if (tipoClienteidTipoClienteOld != null && !tipoClienteidTipoClienteOld.equals(tipoClienteidTipoClienteNew)) {
tipoClienteidTipoClienteOld.getClienteCollection().remove(cliente);
tipoClienteidTipoClienteOld = em.merge(tipoClienteidTipoClienteOld);
}
if (tipoClienteidTipoClienteNew != null && !tipoClienteidTipoClienteNew.equals(tipoClienteidTipoClienteOld)) {
tipoClienteidTipoClienteNew.getClienteCollection().add(cliente);
tipoClienteidTipoClienteNew = em.merge(tipoClienteidTipoClienteNew);
}
for (Anuncio anuncioCollectionNewAnuncio : anuncioCollectionNew) {
if (!anuncioCollectionOld.contains(anuncioCollectionNewAnuncio)) {
Cliente oldClienteidClienteOfAnuncioCollectionNewAnuncio = anuncioCollectionNewAnuncio.getClienteidCliente();
anuncioCollectionNewAnuncio.setClienteidCliente(cliente);
anuncioCollectionNewAnuncio = em.merge(anuncioCollectionNewAnuncio);
if (oldClienteidClienteOfAnuncioCollectionNewAnuncio != null && !oldClienteidClienteOfAnuncioCollectionNewAnuncio.equals(cliente)) {
oldClienteidClienteOfAnuncioCollectionNewAnuncio.getAnuncioCollection().remove(anuncioCollectionNewAnuncio);
oldClienteidClienteOfAnuncioCollectionNewAnuncio = em.merge(oldClienteidClienteOfAnuncioCollectionNewAnuncio);
}
}
}
for (Usuario usuarioCollectionNewUsuario : usuarioCollectionNew) {
if (!usuarioCollectionOld.contains(usuarioCollectionNewUsuario)) {
Cliente oldClienteidClienteOfUsuarioCollectionNewUsuario = usuarioCollectionNewUsuario.getClienteidCliente();
usuarioCollectionNewUsuario.setClienteidCliente(cliente);
usuarioCollectionNewUsuario = em.merge(usuarioCollectionNewUsuario);
if (oldClienteidClienteOfUsuarioCollectionNewUsuario != null && !oldClienteidClienteOfUsuarioCollectionNewUsuario.equals(cliente)) {
oldClienteidClienteOfUsuarioCollectionNewUsuario.getUsuarioCollection().remove(usuarioCollectionNewUsuario);
oldClienteidClienteOfUsuarioCollectionNewUsuario = em.merge(oldClienteidClienteOfUsuarioCollectionNewUsuario);
}
}
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = cliente.getIdCliente();
if (findCliente(id) == null) {
throw new NonexistentEntityException(“The cliente 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();
Cliente cliente;
try {
cliente = em.getReference(Cliente.class, id);
cliente.getIdCliente();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException(“The cliente with id " + id + " no longer exists.”, enfe);
}
List illegalOrphanMessages = null;
Collection anuncioCollectionOrphanCheck = cliente.getAnuncioCollection();
for (Anuncio anuncioCollectionOrphanCheckAnuncio : anuncioCollectionOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList();
}
illegalOrphanMessages.add(“This Cliente (” + cliente + “) cannot be destroyed since the Anuncio " + anuncioCollectionOrphanCheckAnuncio + " in its anuncioCollection field has a non-nullable clienteidCliente field.”);
}
Collection usuarioCollectionOrphanCheck = cliente.getUsuarioCollection();
for (Usuario usuarioCollectionOrphanCheckUsuario : usuarioCollectionOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList();
}
illegalOrphanMessages.add(“This Cliente (” + cliente + “) cannot be destroyed since the Usuario " + usuarioCollectionOrphanCheckUsuario + " in its usuarioCollection field has a non-nullable clienteidCliente field.”);
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
TipoCliente tipoClienteidTipoCliente = cliente.getTipoClienteidTipoCliente();
if (tipoClienteidTipoCliente != null) {
tipoClienteidTipoCliente.getClienteCollection().remove(cliente);
tipoClienteidTipoCliente = em.merge(tipoClienteidTipoCliente);
}
em.remove(cliente);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}public List findClienteEntities() {
return findClienteEntities(true, -1, -1);
}public List findClienteEntities(int maxResults, int firstResult) {
return findClienteEntities(false, maxResults, firstResult);
}private List findClienteEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery(“select object(o) from Cliente as o”);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}public Cliente findCliente(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Cliente.class, id);
} finally {
em.close();
}
}public int getClienteCount() {
EntityManager em = getEntityManager();
try {
Query q = em.createQuery(“select count(o) from Cliente as o”);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
[/code]
Classe de Teste -
[code]public static void main(String args[]) throws IllegalOrphanException, NonexistentEntityException, Exception
{
//EntityManagerFactory emf = Persistence.createEntityManagerFactory(“CGPU”);
//EntityManager em = emf.createEntityManager();
//em.getTransaction().begin();
CadastroCliente cadastro = new CadastroCliente();
CadastroTipoCliente cadastroTipo = new CadastroTipoCliente();
TipoCliente tipo = cadastroTipo.findTipoCliente(2);
Cliente cliente = cadastro.findCliente(7);
cliente.setCpfCnpj("047");
cliente.setTipoClienteidTipoCliente(tipo);
cliente.setAnuncioCollection(null);
cadastro.edit(cliente);
/*em.persist(cliente);
em.getTransaction().commit();
em.close();
emf.close();*/
}[/code]
DESCULPEM A QUANTIDADE DE CÓDIGO! mas nao vi outra forma de tentar descobrir o erro com vcs senao mostrando parte do codigo.
Se puderem me ajudar agradeço a todos.