- Сортировка с помощью JPA
- Дальнейшее чтение:
- Spring Data JPA @Query
- JPA конвертеры атрибутов
- Работаем с Kotlin и JPA
- 2. Сортировка с помощью JPA / JQL API
- 2.1. Установка порядка сортировки
- 2.2. Сортировка по более чем одному атрибуту
- 2.3. Установка приоритета сортировки нулевых значений
- 2.4. Сортировка отношений один ко многим
- 3. Сортировка с помощью API объекта запроса критериев JPA
- 3.1. Сортировка по более чем одному атрибуту
- 4. Заключение
- Java jpa order by
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- JPA — Using @OrderBy Annotation
- When @OrderBy used with @ElementCollection
- When @OrderBy used with a relationship
- @OrderBy vs @OrderColumn
- Example
- Entities
- Table mappings
- Retrieval of collections
- Example Project
- JPA Criteria API — ORDER BY in Criteria Queries
- Example
- Entity
- Using Criteria API to apply ordering
- Example Project
Сортировка с помощью JPA
Эта статья иллюстрирует различные способыJPA can be used for sorting.
Дальнейшее чтение:
Spring Data JPA @Query
Узнайте, как использовать аннотацию @Query в Spring Data JPA для определения пользовательских запросов с использованием JPQL и собственного SQL.
JPA конвертеры атрибутов
Посмотрите на сопоставление типов JDBC с классами Java в JPA с помощью преобразователей атрибутов.
Работаем с Kotlin и JPA
Узнайте, как вы можете использовать JPA в своем проекте Kotlin.
2. Сортировка с помощью JPA / JQL API
Использование JQL для сортировки осуществляется с помощью предложенияOrder By:
String jql ="Select f from Foo as f order by f.id"; Query query = entityManager.createQuery (jql);
На основе этого запроса JPA генерирует следующие простыеSQL statement:
Hibernate: select foo0_.id as id1_4_, foo0_.name as name2_4_ from Foo foo0_ order by foo0_.id
Обратите внимание, что ключевые слова SQL в строке JQL не чувствительны к регистру, но имена объектов и их атрибуты.
2.1. Установка порядка сортировки
По умолчаниюthe sorting order is ascending, но его можно явно указать в строке JQL. Как и в чистом SQL, варианты упорядочения:asc иdesc:
String jql = "Select f from Foo as f order by f.id desc"; Query sortQuery = entityManager.createQuery(jql);
Затемgenerated SQL query будет включать направление заказа:
Hibernate: select foo0_.id as id1_4_, foo0_.name as name2_4_ from Foo foo0_ order by foo0_.id desc
2.2. Сортировка по более чем одному атрибуту
Для сортировки по нескольким атрибутам они добавляются в предложение order by строки JQL:
String jql ="Select f from Foo as f order by f.name asc, f.id desc"; Query sortQuery = entityManager.createQuery(jql);
Оба условия сортировки появятся в оператореgenerated SQL query:
Hibernate: select foo0_.id as id1_4_, foo0_.name as name2_4_ from Foo foo0_ order by foo0_.name asc, foo0_.id desc
2.3. Установка приоритета сортировки нулевых значений
Приоритет значений NULL по умолчанию зависит от базы данных, но его можно настроить с помощью предложенияNULLS FIRST илиNULLS LAST в строке запроса HQL.
Вот простой пример — упорядочитьname изFoo в порядке убывания и разместитьNulls в конце:
Query sortQuery = entityManager.createQuery ("Select f from Foo as f order by f.name desc NULLS LAST");
Сгенерированный SQL-запрос включаетis null the 1 else 0 end clause (3-я строка):
Hibernate: select foo0_.id as id1_4_, foo0_.BAR_ID as BAR_ID2_4_, foo0_.bar_Id as bar_Id2_4_, foo0_.name as name3_4_,from Foo foo0_ order by case when foo0_.name is null then 1 else 0 end, foo0_.name desc
2.4. Сортировка отношений один ко многим
Пройдя мимо основных примеров, давайте теперь рассмотрим вариант использования, включающийsorting entities in a one to many relation —Bar, содержащий набор сущностейFoo.
Мы хотим отсортировать сущностиBar, а также их коллекцию сущностейFoo — JPA особенно прост для этой задачи:
@OrderBy("name ASC") List fooList;
String jql = "Select b from Bar as b order by b.id"; Query barQuery = entityManager.createQuery(jql); List barList = barQuery.getResultList();
Обратите внимание, что аннотация@OrderBy является необязательной, но мы используем ее в этом случае, потому что мы хотим отсортировать коллекциюFoo для каждогоBar.
Давайте посмотрим наSQL query, отправленные в RDMS:
Hibernate: select bar0_.id as id1_0_, bar0_.name as name2_0_ from Bar bar0_ order by bar0_.id Hibernate: select foolist0_.BAR_ID as BAR_ID2_0_0_, foolist0_.id as id1_4_0_, foolist0_.id as id1_4_1_, foolist0_.BAR_ID as BAR_ID2_4_1_, foolist0_.bar_Id as bar_Id2_4_1_, foolist0_.name as name3_4_1_ from Foo foolist0_ where foolist0_.BAR_ID=? order by foolist0_.name asc
Первый запрос сортирует родительскую сущностьBar. Второй запрос создается для сортировки коллекции дочерних сущностейFoo, принадлежащихBar.
3. Сортировка с помощью API объекта запроса критериев JPA
С критериями JPA — методorderBy является «универсальной» альтернативой для установки всех параметров сортировки: могут быть установлены какorder direction, так иattributes to sort by. Ниже приводится API метода:
- orderBy (CriteriaBuilder.asc): сортировка по возрастанию.
- orderBy (CriteriaBuilder.desc): сортировка по убыванию.
Каждый экземплярOrder создается с помощью объекта CriteriaBuilder с помощью его методовasc илиdesc.
Вот быстрый пример — сортировкаFoos по ихname:
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); Root from = criteriaQuery.from(Foo.class); CriteriaQuery select = criteriaQuery.select(from); criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
Аргумент методаget чувствителен к регистру, так как он должен соответствовать имени атрибута.
В отличие от простого JQL, API-интерфейс объекта запроса критериев JPAforces an explicit order directionв запросе. Обратите внимание, что в последней строке этого фрагмента кода объектcriteriaBuilder указывает порядок сортировки по возрастанию, вызывая свой методasc.
Когда приведенный выше код выполняется, JPA генерирует SQL-запрос, показанный ниже. Объект критериев JPA генерирует оператор SQL с явным предложениемasc:
Hibernate: select foo0_.id as id1_4_, foo0_.name as name2_4_ from Foo foo0_ order by foo0_.name asc
3.1. Сортировка по более чем одному атрибуту
Для сортировки по более чем одному атрибуту просто передайте экземплярOrder методуorderBy для каждого атрибута, по которому выполняется сортировка.
Вот быстрый пример — сортировка поname иid, в порядкеasc иdesc соответственно:
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); Root from = criteriaQuery.from(Foo.class); CriteriaQuery select = criteriaQuery.select(from); criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id")));
Соответствующий SQL-запрос показан ниже:
Hibernate: select foo0_.id as id1_4_, foo0_.name as name2_4_ from Foo foo0_ order by foo0_.name asc, foo0_.id desc
4. Заключение
В этой статье рассматриваются альтернативы сортировки в Java Persistence API, для простых сущностей, а также для сущностей в отношении «один ко многим». Эти подходы делегируют бремя сортировки на уровень базы данных.
Реализация этого руководства по сортировке JPA можно найти вthe GitHub project — это проект на основе Maven, поэтому его должно быть легко импортировать и запускать как есть.
Java jpa order by
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
JPA — Using @OrderBy Annotation
The annotation @OrderBy Specifies the ordering of the elements of a collection valued association or element collection at the point when the association or collection is retrieved.
This annotation can be used with @ElementCollection or @OneToMany / @ManyToMany relationships.
When @OrderBy used with @ElementCollection
If the collection is of basic type, then ordering will be by the value of the basic objects. For example following will arrange phoneNumbers in their natural ordering:
@ElementCollection @OrderBy private List phoneNumbers;
If the collection is of @Embeddable type, the dot («.») notation is used to refer to an attribute within the embedded attribute. For example following will arrange addresses by country names.
@ElementCollection @OrderBy("city.country DESC") private List addresses;
Where Address is defined as:
@Embeddable public class Address
ASC | DESC can be used to specify whether ordering is ascending or descending. Default is ASC.
When @OrderBy used with a relationship
@OrderBy only works with direct properties if used with a relationship ( @OneToMany or @ManyToMany ). For example:
@ManyToMany @OrderBy("supervisor") private List tasks;
Dot («.») access doesn’t work in case of relationships. Attempting to use a nested property e.g. @OrderBy(«supervisor.name») will end up in a runtime exception.
If the ordering element is not specified for an entity association (i.e. the annotation is used without any value), ordering by the primary key of the associated entity is assumed. For example:
@ManyToMany @OrderBy private List tasks;
In above case tasks collection will be ordered by Task#id.
@OrderBy vs @OrderColumn
The order specified by @OrderBy is only applied during runtime when a query result is retrieved.
Whereas, the usage of @OrderColumn (last tutorials ) results in a permanent ordering of the related data. In this case a dedicated database column is used to maintain the ordering.
Example
Entities
@Entity public class Employee < @Id @GeneratedValue private long id; private String name; @ElementCollection @OrderBy//order by strings private ListphoneNumbers; @ManyToMany(cascade = CascadeType.ALL) @OrderBy("supervisor")//order by task.supervisor (employee.id) private List tasks; @ElementCollection @OrderBy("city.country DESC")//desc order by address.city.country private List addresses; . >
@Embeddable public class Address
@Embeddable public class City
Table mappings
Let’s see our entities are mapped to what database tables:
public class TableMappingMain < private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("example-unit"); public static void main(String[] args) < try < nativeQuery("SHOW TABLES"); nativeQuery("SHOW COLUMNS FROM EMPLOYEE"); nativeQuery("SHOW COLUMNS FROM EMPLOYEE_PHONENUMBERS"); nativeQuery("SHOW COLUMNS FROM EMPLOYEE_TASK"); nativeQuery("SHOW COLUMNS FROM TASK"); nativeQuery("SHOW COLUMNS FROM EMPLOYEE_ADDRESSES"); >finally < entityManagerFactory.close(); >> public static void nativeQuery(String s) < EntityManager em = entityManagerFactory.createEntityManager(); System.out.printf("'%s'%n", s); Query query = em.createNativeQuery(s); List list = query.getResultList(); for (Object o : list) < if (o instanceof Object[]) < System.out.println(Arrays.toString((Object[]) o)); >else < System.out.println(o); >> em.close(); > >
'SHOW TABLES'
[EMPLOYEE, PUBLIC]
[EMPLOYEE_ADDRESSES, PUBLIC]
[EMPLOYEE_PHONENUMBERS, PUBLIC]
[EMPLOYEE_TASK, PUBLIC]
[TASK, PUBLIC]
'SHOW COLUMNS FROM EMPLOYEE'
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
'SHOW COLUMNS FROM EMPLOYEE_PHONENUMBERS'
[EMPLOYEE_ID, BIGINT(19), NO, , NULL]
[PHONENUMBERS, VARCHAR(255), YES, , NULL]
'SHOW COLUMNS FROM EMPLOYEE_TASK'
[EMPLOYEE_ID, BIGINT(19), NO, , NULL]
[TASKS_ID, BIGINT(19), NO, , NULL]
'SHOW COLUMNS FROM TASK'
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
[SUPERVISOR_ID, BIGINT(19), YES, , NULL]
'SHOW COLUMNS FROM EMPLOYEE_ADDRESSES'
[EMPLOYEE_ID, BIGINT(19), NO, , NULL]
[COUNTRY, VARCHAR(255), YES, , NULL]
[NAME, VARCHAR(255), YES, , NULL]
[STREET, VARCHAR(255), YES, , NULL]
Retrieval of collections
public class ExampleMain < private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("example-unit"); public static void main(String[] args) < try < persistEmployees(); findEmployees(); >finally < entityManagerFactory.close(); >> public static void persistEmployees() < Task task1 = Task.create("Development"); Task task2 = Task.create("Documentation"); Task task3 = Task.create("Designing"); Task task5 = Task.create("Refactoring"); Task task6 = Task.create("Testing"); Employee employee1 = Employee.create("Diana", Arrays.asList(task1, task2, task6), Arrays.asList(Address.create("111 Round Drive", "Papineau", "Sundland"), Address.create("2623 Elmwood Avenue", "Scottsdale", "Zwonga")), "111-111-111", "666-666-666", "222-222-222"); Employee employee2 = Employee.create("Denise", Arrays.asList(task2, task3), Arrays.asList(Address.create("23 Estate Avenue", "Papineau", "Ugrela"), Address.create("367 Rose Route", "Scottsdale", "Mreyton")), "444-444-444", "333-333-333"); Employee employee3 = Employee.create("Linda", Arrays.asList(task1, task5), Arrays.asList(Address.create("345 Little Way", "Fries", "Tospus"), Address.create("91 Vine Lane", "Binesville", "Oblijan")), "555-555-555"); EntityManager em = entityManagerFactory.createEntityManager(); task1.setSupervisor(employee2); task2.setSupervisor(employee1); task3.setSupervisor(employee3); task5.setSupervisor(employee1); task6.setSupervisor(employee3); em.getTransaction().begin(); em.persist(employee1); em.persist(employee2); em.persist(employee3); em.getTransaction().commit(); >private static void findEmployees() < EntityManager em = entityManagerFactory.createEntityManager(); Listemployees = em.createQuery("Select e from Employee e") .getResultList(); for (Employee employee : employees) < System.out.println("---"); System.out.println(employee); System.out.println("-- Tasks --"); for (Task task : employee.getTasks()) < System.out.println("task: " + task); System.out.println("supervisor: " + task.getSupervisor()); >System.out.println("-- addresses --"); employee.getAddresses().forEach(System.out::println); > > >
---
Employee
-- Tasks --
task: Task
supervisor: Employee
task: Task
supervisor: Employee
task: Task
supervisor: Employee
-- addresses --
Address>
Address>
---
Employee
-- Tasks --
task: Task
supervisor: Employee
task: Task
supervisor: Employee
-- addresses --
Address>
Address>
---
Employee
-- Tasks --
task: Task
supervisor: Employee
task: Task
supervisor: Employee
-- addresses --
Address>
Address>
As seen above:
Each employee’s phoneNumbers collection elements are arranged in their natural ordering.
Each employee’s tasks collection elements are arranged by supervisor’s ids.
Each employee’s addresses collection elements are arranged in descending order by the country names.
Example Project
Dependencies and Technologies Used:
- h2 1.4.197: H2 Database Engine.
- hibernate-core 5.2.13.Final: The core O/RM functionality as provided by Hibernate.
Implements javax.persistence:javax.persistence-api version 2.1 - JDK 1.8
- Maven 3.3.9
JPA Criteria API — ORDER BY in Criteria Queries
In Criteria API ordering can be applied by using following method of CriteriaQuery :
CriteriaQuery orderBy(Order. o);
The instance of Order arguments can be created by following methods of CriteriaBuilder :
Following code snippet applies order by (both asc and desc) to two columns:
CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery query = cb.createQuery(Employee.class);//create query object Root employee = query.from(Employee.class);//create object representing 'from' part query.select(employee);//create 'select from' part query.orderBy( cb.asc(employee.get(Employee_.dept)), cb.desc(employee.get(Employee_.salary)) );
Example
Entity
@Entity public class Employee
Using Criteria API to apply ordering
public class ExampleMain < private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("example-unit"); public static void main(String[] args) < try < persistEmployees(); findEmployeeOrderBySalary(); findEmployeeOrderByDeptAndSalary(); >finally < entityManagerFactory.close(); >> public static void persistEmployees() < Employee employee1 = Employee.create("Diana", 2000, "IT"); Employee employee2 = Employee.create("Rose", 3500, "Admin"); Employee employee3 = Employee.create("Denise", 2500, "Admin"); Employee employee4 = Employee.create("Mike", 4000, "IT"); Employee employee5 = Employee.create("Linda", 4500, "Sales"); EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); em.persist(employee1); em.persist(employee2); em.persist(employee3); em.persist(employee4); em.persist(employee5); em.getTransaction().commit(); em.close(); >private static void findEmployeeOrderBySalary() < System.out.println("-- All employees order by salary --"); EntityManager em = entityManagerFactory.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQueryquery = cb.createQuery(Employee.class);//query object Root employee = query.from(Employee.class);//from part query.select(employee);//'select from' part query.orderBy(cb.desc(employee.get(Employee_.salary)));//order by part TypedQuery typedQuery = em.createQuery(query); typedQuery.getResultList() .forEach(System.out::println); em.close(); > private static void findEmployeeOrderByDeptAndSalary() < System.out.println("-- All employees order by dept and salary --"); EntityManager em = entityManagerFactory.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQueryquery = cb.createQuery(Employee.class);//query object Root employee = query.from(Employee.class);//from part query.select(employee);//'select from' part query.orderBy( cb.asc(employee.get(Employee_.dept)), cb.desc(employee.get(Employee_.salary)) );//order by part TypedQuery typedQuery = em.createQuery(query); typedQuery.getResultList() .forEach(System.out::println); em.close(); > >
-- All employees order by salary --
Employee
Employee
Employee
Employee
Employee
-- All employees order by dept and salary --
Employee
Employee
Employee
Employee
Employee
Example Project
Dependencies and Technologies Used:
- h2 1.4.197: H2 Database Engine.
- hibernate-core 5.3.2.Final: Hibernate’s core ORM functionality.
Implements javax.persistence:javax.persistence-api version 2.2 - hibernate-jpamodelgen 5.3.2.Final: Annotation Processor to generate JPA 2 static metamodel classes.
- JDK 1.8
- Maven 3.5.4