Named query not known - Hibernate + JSF

Asked

Viewed 34 times

0

Personal talk,

I’m having trouble calling a named query, resulting in org.hibernate.MappingException: Named query not known

Hibernate.cfg.xml:

    <hibernate-configuration>
      <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/lopi?zeroDateTimeBehavior=convertToNull </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>

        <property name="hibernate.hbm2ddl.auto">update</property>

  </session-factory>
</hibernate-configuration>

persistence.xml:

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="org.primefaces_icarus_war_2.0.0PU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <jta-data-source>java::app/icarus</jta-data-source>
    <class>br.lopi.model.Empresa</class>
    <class>br.lopi.model.Usuario</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/lopi?zeroDateTimeBehavior=CONVERT_TO_NULL"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value="123456"/>
    </properties>
  </persistence-unit>
</persistence>

Class of ethics:

@Entity
@Table(name = "EMPRESA")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Empresa.findAll", query = "SELECT e FROM Empresa e"),
    @NamedQuery(name = "Empresa.findById", query = "SELECT e FROM Empresa e WHERE e.id = :id"),
    @NamedQuery(name = "Empresa.findByNomefantasia", query = "SELECT e FROM Empresa e WHERE e.nomefantasia = :nomefantasia"),
    @NamedQuery(name = "Empresa.findByRazaosocial", query = "SELECT e FROM Empresa e WHERE e.razaosocial = :razaosocial"),
    @NamedQuery(name = "Empresa.findByCnpj", query = "SELECT e FROM Empresa e WHERE e.cnpj = :cnpj")})
public class Empresa implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Size(max = 45)
    @Column(name = "NOMEFANTASIA")
    private String nomefantasia;
...

Where I call the query:

    public List<Empresa> listar() {
    Session sessao = null;
    try {
        sessao = HibernateUtil.getSessionFactory().openSession();

        return sessao.getNamedQuery("Empresa.findAll").list();


    }
    catch(HibernateException ex) {
        throw ex;
    }
    finally {            
        if(sessao != null && sessao.isOpen())
            sessao.close();

    }
}

Error:

com.sun.faces.mgbean.ManagedBeanCreationException: Um erro ocorreu ao realizar a injeção de recurso no bean gerenciado usuarioController
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:227)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:94)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:137)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
    at javax.faces.component.UIInput.getValue(UIInput.java:291)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:109)
    at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:73)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeMarkup(InputTextRenderer.java:92)
    at org.primefaces.component.inputtext.InputTextRenderer.encodeEnd(InputTextRenderer.java:62)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.primefaces.icarus.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:32)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:609)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1623)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.sun.faces.spi.InjectionProviderException
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:115)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:95)
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
    ... 60 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:113)
    ... 62 more
Caused by: org.hibernate.MappingException: Named query not known: Empresa.findAll
    at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
    at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1368)
    at br.lopi.DAO.EmpresaDAO.listar(EmpresaDAO.java:39)
    at br.lopi.service.EmpresaService.listar(EmpresaService.java:13)
    at br.lopi.controller.UsuarioController.inicializar(UsuarioController.java:25)
    ... 67 more

I believe it is some problem in the settings of Hibernate, but I have searched enough and I have not found what it is.

If anyone can shed some light, I’d really appreciate it.

  • 1

    Strange you have both Xmls files, seems redundant. Are you sure your system is configured correctly? He seems to be ignoring persistence.xml. There, he does not find the entity and its named query is not found. Something else, what class Entity is importing?

  • You’re wrong! persistence.xml was redundant, it was enough to map the classes in Hibernate.cfg and it’s solved. Thanks!

1 answer

1


Apparently it has a redundancy in its configuration.

You have two files xml configuring the Hibernate:

  • Hibernate.cfg.xml
  • persistence.xml

Only in cases very specific you would use both, referencing one of them to the other. But the default is to have only one of them.

How are you using SessionFactory, is likely that the system is considering only the hibernate.cfg.xml. That is, your configuration is just ignoring the configuration file you declared the entities with <class />, the persistence.xml.

One solution is to map the entities in the hibernate.cfg.xml and possibly remove the persistence.xml.

Another cause for this error is to have imported the Entity incorrect. Make sure you are using the javax.persistence.Entity

Browser other questions tagged

You are not signed in. Login or sign up in order to post.