using HQL queries in Spring Boot
Asked Answered
I

3

6

I have a Spring Boot project which has multiple Model class

I want to use multiple model classes in my DAO implementation.

Can someone please explain how can I use HQL queries here.

Most of the examples i saw uses CRUDRepository. But in my understanding this limits us to one model class (please correct me if my understanding is wrong).

Secondly using CRUDRepository limits me to very specific methods. But HQL queries I need could be more complex like:

Query query = session.createQuery(from Employee where name=:name and place=:place and phone=:phone and gender=:gender);

Is it standard practice to use CRUDRepository even for HQL queries like this. Otherwise how can I use such HQL queries. (If possible please also add what all dependencies and annotations i will need to add). I am using Hibernate and postgres.

Inception answered 19/12, 2017 at 20:27 Comment(1)
Here's the documentation. It contains answers to all your questions, and more: docs.spring.io/spring-data/jpa/docs/current/reference/html/…Durward
G
5

If you wish to execute dynamic HQL queries without using repositories, etc, this works for me really nicely:

    @Autowired
    EntityManager entityManager;

    @RequestMapping("/query")
    @ResponseBody
    public String testQuery() {

        Query query = entityManager.createQuery("select u from User u");
        List<User> users = query.getResultList();
        users.forEach(u -> System.out.println(u.getFirstname()));
        return "See Console";
    }

The nice thing about it is that if you're quickly wanting to test a query, and you're using something like Spring LiveReload, JRebel, DCEVM or HotSwap with Hybris, you can change the query and save and refresh.

Grimace answered 17/9, 2019 at 6:6 Comment(0)
H
1

CRUD repositories are the standard way to write a DAO. If you look at the documentations, you will see that you can have complex queries that uses the fields of the entity (which can be pretty complex, I encourage you to look here at the query methods part - 4.3), and if you want even more complex methods, you can use the annotation @Query over a method:

@Repository
interface MyRepo implements JpaRepository<MyEntity,Long> {
     @Query("your custom query here")
     MyEntity findByFeature(String a)
}

Now you can insert you query and access you String a inside the query (like Select u where u.name="blabla" where blabla is your input string)

The @Query comes with the same dependency as the repositories (I think that spring-boot-starter-data-jpa is enough)

Harrar answered 19/12, 2017 at 20:44 Comment(0)
I
1

JpaRepository is surely awesome to use, but for someone who has to use complex HQL queries (due to your organization's recommendations etc), here is how i did it:

  1. Get Session factory by injecting following bean in your configuration:

    @Bean public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) { return emf.unwrap(SessionFactory.class); }

  2. Add EntityScan and ComponentScan to your configuration class

    @EntityScan(basePackages = { "com.app.persistence" }) @ComponentScan(basePackages = { "com.app" })

  3. Go ahead and use any HQL queries:

    @Autowired SessionFactory factory;

    @Override
    public String check() {
        Session session = null;
        try {
            session = factory.openSession();
            Query query = session.createQuery("from Test");
            List<Test> res = query.list();
            Test sing = res.get(0);
            return sing.getName();
    
        } catch (Exception e) {
            System.out.println("Exception in Dao");
            e.printStackTrace();
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
    

Note: I am assuming that other things like configuring DataSource and all have been taken care already.

Anyone can feel free to correct me if my understanding or way was wrong.

But it worked well for me this way!! :)

Inception answered 20/12, 2017 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.