Introduction to query and query language in the Gorm framework
The Gorm framework is a development tool for providing a unified ORM (object-relationship mapping) solution between Groovy and Java.It is part of the Grails framework, but it can also be used alone for Java development.
Gorm supports multiple query methods, including object -oriented query grammar and Hibernate's HQL (Hibernate Query Language).Through GORM, developers can extract and operate data from the database in a simple and intuitive way.
Inquiry summary:
1. Query all data: Use the `.list ()` method to get all the records in the database.
List<Book> books = Book.list();
2. In query data according to ID: Use the `.get ()` method to obtain the records in the table according to the main key.
Book book = Book.get(1);
3. Inquiry data according to the condition: You can use the where method to add query conditions, and use the `.list ()` method to obtain the record of the condition.
List<Book> books = Book.where {
author == "John Smith" && year == 2021
}.list();
4. Sorting query results: Use the `.listOrderby ()` method to sort the query results.
List<Book> books = Book.listOrderBy("year", "desc");
5. Pagling query: You can use `.list (max: n, offset: m)` method for pagination query. Among them, `max` represents the number of records per page, and` Offset` indicates the offset.
List<Book> books = Book.list(max: 10, offset: 20);
6. Polymerization function query: Gorm supports a variety of aggregate functions, such as `.count ()`, `.sum ()`, `.min (),` .max (), `.avg ()`, etc.
int bookCount = Book.count();
7. Projection query: Use `.list (Projects.property (" Column ")` method can be projected and query, only obtain the specified column data.
List<String> authors = Book.list(projections.property("author"));
Query language introduction:
In addition to the above query method, Gorm also supports more complicated query using Hibernate's HIQL (Hibernate Query Language).HQL allows developers to write query statements similar to SQL, but operate entity objects in an object -oriented manner.
For example, use HQL to query all authors "John Smith" books::
List<Book> books = Book.findAll("from Book as b where b.author = ?", "John Smith");
Use HQL for association query:
List<Book> books = Book.executeQuery("select b from Book as b join b.author as a where a.name = ?", "John Smith");
Use HQL for pagination query:
List<Book> books = Book.executeQuery("from Book", [max: 10, offset: 20]);
Summarize:
The Gorm framework provides a variety of simple and easy -to -use query methods, enabling developers to easily extract and operate data from the database.Whether using object -oriented query grammar or HQL, developers can choose the most suitable query method according to the needs.This enables developers to write database query code more efficiently and improve development efficiency.