Junior — Middle
Can you explain what is meant by using native SQL queries in the @Query annotation in Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, the @Query annotation allows you to write queries to retrieve data. By default, this is HQL (Hibernate Query Language) — an object-oriented query language. However, if you need to use a native SQL query, you can specify the parameter nativeQuery = true in @Query.
This means that the query will be executed directly as SQL, without Hibernate transformation. This is useful when you need to use database-specific functions or complex queries that are difficult to express in HQL.
Example:
@Query(value = "SELECT * FROM users WHERE status = ?1", nativeQuery = true)
List<User> findUsersByStatusNative(String status);
Here, users is the name of the table in the database, not the entity name. Such a query will be executed directly in the database.