Jpa @elementcollection 의 데이터 정렬 @orderby

jpa @column name order by @elementcollection @orderby

JPA - Using @OrderBy Annotation

[Updated: Jun 9, 2018, Created: Jun 9, 2018]

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<String> 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<Address> addresses;

Where Address is defined as:

 @Embeddable
 public class Address {
  ...
  @Embedded
  private City city 
  ....
 }

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<Task> tasks;

Where Task entity is:

 @Entity
 public class Task {
    ....
    @OneToOne
    private Employee supervisor;
    ...
}

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:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

  @ManyToMany
  @OrderBy
  private List<Task> 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 List<String> phoneNumbers;

  @ManyToMany(cascade = CascadeType.ALL)
  @OrderBy("supervisor")//order by task.supervisor (employee.id)
  private List<Task> tasks;

  @ElementCollection
  @OrderBy("city.country DESC")//desc order by address.city.country
  private List<Address> addresses;
    .............
}
@Entity
public class Task {
  @Id
  @GeneratedValue
  private long id;
  private String name;
  @OneToOne
  private Employee supervisor;
    .............
}
@Embeddable
public class Address {
  private String street;
  @Embedded
  private City city;
    .............
}
@Embeddable
public class City {
  private String name;
  private String country;
    .............
}

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]

H2 database SHOW statements

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();
      List<Employee> employees = 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{id=1, name='Diana', phoneNumbers=[111-111-111, 222-222-222, 666-666-666]}
-- Tasks --
task: Task{id=3, name='Documentation'}
supervisor: Employee{id=1, name='Diana', phoneNumbers=[111-111-111, 222-222-222, 666-666-666]}
task: Task{id=2, name='Development'}
supervisor: Employee{id=5, name='Denise', phoneNumbers=[333-333-333, 444-444-444]}
task: Task{id=4, name='Testing'}
supervisor: Employee{id=7, name='Linda', phoneNumbers=[555-555-555]}
-- addresses --
Address{street='2623  Elmwood Avenue', city=City{name='Scottsdale', country='Zwonga'}}
Address{street='111 Round Drive', city=City{name='Papineau', country='Sundland'}}
---
Employee{id=5, name='Denise', phoneNumbers=[333-333-333, 444-444-444]}
-- Tasks --
task: Task{id=3, name='Documentation'}
supervisor: Employee{id=1, name='Diana', phoneNumbers=[111-111-111, 222-222-222, 666-666-666]}
task: Task{id=6, name='Designing'}
supervisor: Employee{id=7, name='Linda', phoneNumbers=[555-555-555]}
-- addresses --
Address{street='23 Estate Avenue', city=City{name='Papineau', country='Ugrela'}}
Address{street='367 Rose Route', city=City{name='Scottsdale', country='Mreyton'}}
---
Employee{id=7, name='Linda', phoneNumbers=[555-555-555]}
-- Tasks --
task: Task{id=8, name='Refactoring'}
supervisor: Employee{id=1, name='Diana', phoneNumbers=[111-111-111, 222-222-222, 666-666-666]}
task: Task{id=2, name='Development'}
supervisor: Employee{id=5, name='Denise', phoneNumbers=[333-333-333, 444-444-444]}
-- addresses --
Address{street='345 Little Way', city=City{name='Fries', country='Tospus'}}
Address{street='91 Vine Lane', city=City{name='Binesville', country='Oblijan'}}

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
 
 

Java 11 Tutorials

Java 10 Tutorials

Java 9 Tutorials

Recent Tutorials

 @OrderBy Example  Select All  Download 
  • jpa-order-by-annotation-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java
        • resources
          • META-INF
 
package com.logicbig.example;

import javax.persistence.*;
import java.util.Arrays;
import java.util.List;

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private long id;
    private String name;

    @ElementCollection
    @OrderBy//order by strings
    private List<String> phoneNumbers;

    @ManyToMany(cascade = CascadeType.ALL)
    @OrderBy("supervisor")//order by task.supervisor (employee.id)
    private List<Task> tasks;

    @ElementCollection
    @OrderBy("city.country DESC")//desc order by address.city.country
    private List<Address> addresses;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List<String> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

    public List<Task> getTasks() {
        return tasks;
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = tasks;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }

    public static Employee create(String name, List<Task> tasks,
                                  List<Address> addresses,
                                  String... phones) {
        Employee e = new Employee();
        e.setName(name);
        e.setTasks(tasks);
        e.setPhoneNumbers(Arrays.asList(phones));
        e.setAddresses(addresses);
        return e;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", phoneNumbers=" + phoneNumbers +
                '}';
    }
}
 

[출처] https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/order-by-annotation.html

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
27 [java][maven] jar 파일 의존성 한번에 다운로드 maven 사용 졸리운_곰 2023.08.24 192
26 Prometheus + Grafana로 Java 애플리케이션 모니터링하기 file 졸리운_곰 2020.12.17 279
25 Blockchain Implementation With Java Code file 졸리운_곰 2019.06.16 338
24 Java 코드로 이해하는 블록체인(Blockchain) 졸리운_곰 2019.06.16 377
23 순수 Java Application 코드로 Restful api 호출 졸리운_곰 2018.10.10 415
22 WebDAV 구현을 위한 환경 설정 file 졸리운_곰 2017.09.24 268
21 [Java] Apache Commons HttpClient로 SSL 통신하기 졸리운_곰 2017.03.27 784
20 JSoup를 이용한 HTML 파싱 졸리운_곰 2017.03.04 320
19 jsoup을 활용해서 Java에서 HTML 파싱하는 방법 정리 file 졸리운_곰 2017.03.04 579
18 NSA의 Dataflow 엔진 Apache NiFi 소개와 설치 file 졸리운_곰 2017.01.23 630
17 wordpress-java-integration 자바와 워드프레스 통합 졸리운_곰 2016.12.30 298
16 Create New Posts in Wordpress using Java and XMLRpc 졸리운_곰 2016.11.14 268
15 자바로 POST 방식으로 통신하기, java httppost 클래스를 활용한 예제 졸리운_곰 2016.11.14 647
14 [Java]아파치 HttpClient사용하기 file 졸리운_곰 2016.11.14 301
13 Building a Search Engine With Nutch Solr And Hadoop file 졸리운_곰 2016.04.21 435
12 Nutch and Hadoop Tutorial file 졸리운_곰 2016.04.21 391
11 Latest step by Step Installation guide for dummies: Nutch 0. file 졸리운_곰 2016.04.21 305
10 Nutch 초간단 빌드와 실행 졸리운_곰 2016.04.21 681
9 Nutch로 알아보는 Crawling 구조 - Joinc 졸리운_곰 2016.04.21 536
8 A tiny bittorrent library Java: 자바로 만든 작은 bittorrent 라이브러리 file 졸리운_곰 2016.04.20 418
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED