What is HQL in Spring Boot and how to use it

What is HQL in Spring Boot and how to use it

introduction

When developing web applications, we often need to query data from the database. Spring Boot provides multiple ways to query data, one of which is to use HQL (Hibernate Query Language). HQL is an object-oriented query language, similar to SQL, but more flexible and powerful. This article will introduce the basic usage of HQL, with code examples to help readers better understand and use the language.

Insert image description here

What is HQL?

HQL (Hibernate Query Language) is a query language in the Hibernate framework, used to query objects, similar to SQL. Unlike SQL, HQL is an object-based query language that can directly operate on objects instead of tables. HQL supports various query operations, such as querying a single object, querying multiple objects, paging query, sorting, etc. Using HQL can make query operations more flexible and powerful.

How to use HQL?

Before using HQL, you need to configure Hibernate. For specific configuration methods, please refer to the official Spring Boot documentation. Next, we can use HQL in the DAO layer to query the data. Here's a simple example:

@Repository
public class UserDao {
    
    

    @Autowired
    private EntityManager entityManager;

    public User findById(Long id) {
    
    
        String hql = "from User where id = :id";
        TypedQuery<User> query = entityManager.createQuery(hql, User.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    public List<User> findAll() {
    
    
        String hql = "from User";
        TypedQuery<User> query = entityManager.createQuery(hql, User.class);
        return query.getResultList();
    }

}

In the above example, we defined a DAO class named UserDao, in which the findById and findAll methods are used to query a single user and query all users respectively. In both methods, we used HQL to query the data. It should be noted that we use the EntityManager object to execute HQL, rather than using JdbcTemplate or other methods.

Here is a more complex example that demonstrates how to use HQL for paging query and sorting:

@Repository
public class UserDao {
    
    

    @Autowired
    private EntityManager entityManager;

    public Page<User> findPage(int pageNo, int pageSize, String sortField, boolean ascending) {
    
    
        String hql = "select u from User u order by u." + sortField + (ascending ? " asc" : " desc");
        TypedQuery<User> query = entityManager.createQuery(hql, User.class);
        query.setFirstResult((pageNo - 1) * pageSize);
        query.setMaxResults(pageSize);

        List<User> resultList = query.getResultList();
        long totalCount = count();
        return new PageImpl<>(resultList, PageRequest.of(pageNo - 1, pageSize), totalCount);
    }

    public long count() {
    
    
        String hql = "select count(*) from User";
        TypedQuery<Long> query = entityManager.createQuery(hql, Long.class);
        return query.getSingleResult();
    }

}

In the above example, we defined a DAO class named UserDao, in which the findPage method is used to perform paging queries, and the count method is used to query the total number of records. In the findPage method, we use HQL for sorting and paging queries. It should be noted that we use Pageable objects to represent paging information and PageImpl objects to represent query results.

code example

Here is a complete example that demonstrates how to use HQL for querying and pagination:

Entity class:

@Entity
public class User {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

    // 省略 getter 和 setter 方法

}

DAO class:

@Repository
public class UserDao {
    
    

    @Autowired
    private EntityManager entityManager;

    public User findById(Long id) {
    
    
        String hql = "from User where id = :id";
        TypedQuery<User> query = entityManager.createQuery(hql, User.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    public List<User> findAll() {
    
    
        String hql = "from User";
        TypedQuery<User> query = entityManager.createQuery(hql, User.class);
        return query.getResultList();
    }

   public Page<User> findPage(int pageNo, int pageSize, String sortField, boolean ascending) {
    
    
        String hql = "select u from User u order by u." + sortField + (ascending ? " asc" : " desc");
        TypedQuery<User> query = entityManager.createQuery(hql, User.class);
        query.setFirstResult((pageNo - 1) * pageSize);
        query.setMaxResults(pageSize);

        List<User> resultList = query.getResultList();
        long totalCount = count();
        return new PageImpl<>(resultList, PageRequest.of(pageNo - 1, pageSize), totalCount);
    }

    public long count() {
    
    
        String hql = "select count(*) from User";
        TypedQuery<Long> query = entityManager.createQuery(hql, Long.class);
        return query.getSingleResult();
    }

}

Controller class:

@RestController
@RequestMapping("/users")
public class UserController {
    
    

    @Autowired
    private UserDao userDao;

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
    
    
        return userDao.findById(id);
    }

    @GetMapping
    public List<User> findAll() {
    
    
        return userDao.findAll();
    }

    @GetMapping("/page")
    public Page<User> findPage(@RequestParam int pageNo, @RequestParam int pageSize, @RequestParam String sortField, @RequestParam boolean ascending) {
    
    
        return userDao.findPage(pageNo, pageSize, sortField, ascending);
    }

}

In the above example, we defined a UserController class, in which the findById, findAll and findPage methods are used to query a single user, query all users and perform paging queries respectively. In the findPage method, we use HQL for sorting and paging queries. It should be noted that we use Pageable objects to represent paging information and PageImpl objects to represent query results.

Summarize

This article introduces HQL in Spring Boot, explains the basic usage and sample code of HQL. By using HQL, we can query data in the database more flexibly and powerfully. It should be noted that when using HQL, Hibernate needs to be configured and the EntityManager object must be used correctly to execute HQL. Hope this article is helpful to readers.

Guess you like

Origin blog.csdn.net/JasonXu94/article/details/131609547