Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Query defined for that name, when using Entity Manager

I have the following entity:

package com.server.models;
@Entity
@Table(name="users")
@NamedQueries({
    @NamedQuery(name=User.QUERY_FIND_USER,query="SELECT c FROM user c WHERE c.username = :username")
})
public class User {

    public static final String QUERY_FIND_USER = "LoginFindUser";
    //  ...
}

And then using the Entity Manager (em) i'm doing the following:

package com.server.controllers;
@Service
@Transactional
@RestController
@RequestMapping("/user")
public class LoginController {
    @PersistenceContext
    private EntityManager em;
 // my code
    TypedQuery<User> queries = em.createNamedQuery(User.QUERY_FIND_USER,User.class).setParameter("username", username);
    List<User> users = queries.getResultList();
}

However I am getting the following error:

java.lang.IllegalArgumentException: No query defined for that name [LoginFindUser]

Here's my spring-boot Configuration. This should include the scanning of the entity.

package com.server.boot;

@Configuration
@ComponentScan({"com.server"})
@EnableAutoConfiguration
public class Starter {
    public static void main(String[] args){
        SpringApplication.run(Starter.class,args);
        System.out.println("started application");
    }

    @Bean
    public LoginController loginController(){
        return new LoginController();
    }

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
         HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
         factory.setEntityManagerFactory(emf);
         return factory;
    }

}
like image 322
mangusbrother Avatar asked Nov 25 '14 10:11

mangusbrother


People also ask

Which can be used to form a Named Query?

query element is used for HQL named queries and sql-query element is used for native sql named queries. We can use return element for declaring the entity to which resultset will be mapped.

What is named query in JPA?

A named query is a predefined query that you create and associate with a container-managed entity (see "Using Annotations"). At deployment time, OC4J stores named queries on the EntityManager . At run time, you can use the EntityManager to acquire, configure, and execute a named query.

What is Named Query in hibernate?

A named query is a statically defined query with a predefined unchangeable query string. They're validated when the session factory is created, thus making the application to fail fast in case of an error.


1 Answers

Found it. Thanks to the guys in the comments

Add

@EntityScan("com.server.models")

to your configuration class

and I had an error in the query cause user needed to be User

like image 51
mangusbrother Avatar answered Sep 18 '22 12:09

mangusbrother