Olá pessoal, sou novo nesta vida de desenvolvedor, e já me compliquei.
Criei um projeto padrão no Netbeas utilizand JSF. Criei a Classe de entidade de banco Postgre e criei uma página JSF com base nesta classe do banco. Algo bem simples, utilizando somente uma tabela do Banco Postgres e conectando via JDBC. O Pool de conexoes esta OK, pois consigo executar os SQLs no Postgres do próprio Netbeans.
Na primeira aplicação que utilizava o equema “public” deu tudo certo, foram criadas as páginas automatizadas, tudo certinho.
Porém quando criei um modelo utilizando um esquema que não é o principal, ao clicar para exibir os dados da tabela, ocorre o erro na´página:
An Error Occurred: javax.ejb.EJBException ± Stack Trace javax.ejb.EJBException at com.sun.ejb.containers.BaseContainer.processSystemException(BaseCon
LOG do Glassfish:
INFO: file:/C:/Users/denis.GREGEO/Documents/NetBeansProjects/Cat05/build/web/WEB-INF/classes/_Cat05PU logout successful
INFO: Portable JNDI names for EJB CategoriaFacade : [java:global/Cat05/CategoriaFacade, java:global/Cat05/CategoriaFacade!br.com.geomais.beans.CategoriaFacade]
INFO: Inicializando Mojarra 2.0.2 (FCS b10) para o contexto '/Cat05’
INFO: Monitoring jndi:/server/Cat05/WEB-INF/faces-config.xml for modifications
INFO: Loading application Cat05 at /Cat05
INFO: Cat05 was successfully deployed in 726 milliseconds.
AVISO: JSF1063: AVISO! Definindo valor de atributo não serializável em HttpSession (chave: categoriaController, classe do valor: br.com.geomais.JSF.CategoriaController).INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.0.1.v20100213-r6600
GRAVE: Local Exception Stack:
Exception [EclipseLink-8024] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query [Categoria.findAll: SELECT c FROM emasa.categoria c], line 1, column 19: syntax error at [.].
Internal Exception: MismatchedTokenException(83!=78 )
log continua…
Anexo o WAR do projeto
Agradeço a atenção desde já.
Acho que, baseado na descrição do erro abaixo, você pode tentar escrever o jpql diferente sua Classe Categoria está escrita categoria … não seria Categoria dentro do pacote emasa?
Descrição do erro:
Exception Description: Syntax error parsing the query [Categoria.findAll: SELECT c FROM emasa.categoria c], line 1, column 19: syntax error at [.].
Internal Exception: MismatchedTokenException(83!=78 )
No pacote “emasa” esta como categoria mesmo, mas alterei o código cfe sua dica, porém o erro continua.
Abaixo a classe:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.geomais.classes;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* @author denis
*/
@Entity
@Table(name = "Categoria", catalog = "BalnearioCamboriu", schema = "emasa")
@NamedQueries({
@NamedQuery(name = "Categoria.findAll", query = "SELECT c FROM Categoria c"),
@NamedQuery(name = "Categoria.findByCdCategoria", query = "SELECT c FROM Categoria c WHERE c.cdCategoria = :cdCategoria"),
@NamedQuery(name = "Categoria.findByDsCategoria", query = "SELECT c FROM Categoria c WHERE c.dsCategoria = :dsCategoria")})
public class Categoria implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "cd_categoria", nullable = false)
private Integer cdCategoria;
@Column(name = "ds_categoria", length = 2147483647)
private String dsCategoria;
public Categoria() {
}
public Categoria(Integer cdCategoria) {
this.cdCategoria = cdCategoria;
}
public Integer getCdCategoria() {
return cdCategoria;
}
public void setCdCategoria(Integer cdCategoria) {
this.cdCategoria = cdCategoria;
}
public String getDsCategoria() {
return dsCategoria;
}
public void setDsCategoria(String dsCategoria) {
this.dsCategoria = dsCategoria;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cdCategoria != null ? cdCategoria.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 Categoria)) {
return false;
}
Categoria other = (Categoria) object;
if ((this.cdCategoria == null && other.cdCategoria != null) || (this.cdCategoria != null && !this.cdCategoria.equals(other.cdCategoria))) {
return false;
}
return true;
}
@Override
public String toString() {
return "br.com.geomais.classes.Categoria[cdCategoria=" + cdCategoria + "]";
}
}
Você tentou foi exatamente esse?
Não entendi.
Por que a query teria que ter o endereco da pasta onde esta a classe???
[quote=denispoa]Não entendi.
Por que a query teria que ter o endereco da pasta onde esta a classe???[/quote]
Na verdade ele deveria se comportar corretamente e já ter o FQN implicitamente. Mas teste desse jeito e veja o que ocorre!
Quanto ao “endereço da pasta” FQN, se você tiver duas classes com nomes iguais
[code]package sadio;
@Table(“pessoa_1”)
public class Pessoa{}
package sadio.entidade;
@Table(“pessoa_2”)
public class Pessoa{}[/code]
Em vários locais é o jeito de criar a desambiguidade, inclusive em JQPL.
Entendi a desambiguidade da classe.
Quanto a sua dica ocorreu o erro novamente
INFO: Loading application Cat08 at /Cat08
INFO: Cat08 was successfully deployed in 702 milliseconds.
AVISO: JSF1063: AVISO! Definindo valor de atributo não serializável em HttpSession (chave: categoriaController, classe do valor: br.com.geomais.JSF.CategoriaController).
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.0.1.v20100213-r6600
GRAVE: Local Exception Stack:
Exception [EclipseLink-8024] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query [Categoria.findAll: SELECT c FROM br.com.geomais.classes.Categoria c], line 1, column 16: syntax error at [.].
Internal Exception: MismatchedTokenException(83!=78)
at org.eclipse.persistence.exceptions.JPQLException.syntaxErrorAt(JPQLException.java:362)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.handleRecognitionException(JPQLParser.java:304)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.addError(JPQLParser.java:245)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.reportError(JPQLParser.java:362)
at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(Unknown Source)
at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.mismatch(Unknown Source)
at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.match(Unknown Source)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.rangeVariableDeclaration(JPQLParser.java:3575)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.identificationVariableDeclaration(JPQLParser.java:3483)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.fromClause(JPQLParser.java:3367)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectStatement(JPQLParser.java:356)
at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.document(JPQLParser.java:276)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.parse(JPQLParser.java:133)
at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.buildParseTree(JPQLParser.java:94)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:198)
at org.eclipse.persistence.internal.jpa.JPAQuery.processJPQLQuery(JPAQuery.java:106)
at org.eclipse.persistence.internal.jpa.JPAQuery.prepare(JPAQuery.java:90)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:464)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:430)
at org.eclipse.persistence.internal.sessions.AbstractSession.processJPAQueries(AbstractSession.java:1747)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:409)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:671)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:620)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:228)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:369)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:151)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:207)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:202)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.getCriteriaBuilder(EntityManagerWrapper.java:883)
at br.com.geomais.beans.AbstractFacade.findRange(AbstractFacade.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5292)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:157)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:139)
at sun.reflect.GeneratedMethodAccessor239.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:367)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5264)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5252)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:190)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84)
at $Proxy234.findRange(Unknown Source)
at br.com.geomais.beans.__EJB31_Generated__CategoriaFacade__Intf____Bean__.findRange(Unknown Source)
at br.com.geomais.JSF.CategoriaController$1.createPageDataModel(CategoriaController.java:56)
at br.com.geomais.JSF.CategoriaController.getItems(CategoriaController.java:155)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:302)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at com.sun.el.parser.AstValue.getValue(AstValue.java:116)
at com.sun.el.parser.AstValue.getValue(AstValue.java:163)
at com.sun.el.parser.AstEqual.getValue(AstEqual.java:54)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:102)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:416)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1607)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:662)
Caused by: MismatchedTokenException(83!=78)
... 102 more
[quote=denispoa]Entendi a desambiguidade da classe.
Quanto a sua dica ocorreu o erro novamente
[/quote]
Como você está chamando essa namedquery no Query que foi criado apartir do EntityManager, poste o código aqui que executa essa namedquery…
Para tentar lhe responder dei uma estudada na estrtura criada pelo NetBeans.
Ele cria dois Bens sendo uma classe Abstrata que implementa uma classe Facade que extende a Abstrata e Importa a clase Categoria(Código da classe alguns itens acima)
Classe Abstrata
package br.com.geomais.beans;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Classe Facade
package br.com.geomais.beans;
import br.com.geomais.classes.Categoria;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author denis
*/
@Stateless
public class CategoriaFacade extends AbstractFacade<Categoria> {
@PersistenceContext(unitName = "Cat01PU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public CategoriaFacade() {
super(Categoria.class);
}
}
Descobri o que éra!!!
Pesquisando algumas dicas de PostgreSQL + Glassfish, verifiquei que quando se cria a Classe/Bean, tem que utilizar uma sintaxe para nomes do banco, esquemas e colunas conforme segue abaixo:
Exemplo errado na linha 17
package br.com.geomais.classes;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* @author denis
*/
@Entity
@Table(name = "categoria", catalog = "BalnearioCamboriu", schema = "emasa")
@NamedQueries({
@NamedQuery(name = "Categoria.findAll", query = "SELECT c FROM Categoria c"),
@NamedQuery(name = "Categoria.findByCdCategoria", query = "SELECT c FROM Categoria c WHERE c.cdCategoria = :cdCategoria"),
@NamedQuery(name = "Categoria.findByDsCategoria", query = "SELECT c FROM Categoria c WHERE c.dsCategoria = :dsCategoria")})
public class Categoria implements Serializable {
...
Exemplo Correto na linha 17
package br.com.geomais.classes;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* @author denis
*/
@Entity
@Table(name = "categoria", catalog = "\"BalnearioCamboriu\"", schema = "emasa")
@NamedQueries({
@NamedQuery(name = "Categoria.findAll", query = "SELECT c FROM Categoria c"),
@NamedQuery(name = "Categoria.findByCdCategoria", query = "SELECT c FROM Categoria c WHERE c.cdCategoria = :cdCategoria"),
@NamedQuery(name = "Categoria.findByDsCategoria", query = "SELECT c FROM Categoria c WHERE c.dsCategoria = :dsCategoria")})
public class Categoria implements Serializable {
...