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

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
81 SpringBoot JPA 예제(@OneToMany, 단방향) 졸리운_곰 2018.12.31 193
80 JPA OneToOne? 자바 jpa join 졸리운_곰 2018.12.31 203
79 Spring Data JPA 연관관계 매핑하는 방법 졸리운_곰 2018.12.31 179
78 JPA 생성과 수정시 날짜시간 자동삽입 Hibernate generate timestamp on create and update 졸리운_곰 2018.12.13 2089
77 JPA로 insert / update시 날짜시간 자동으로 설정 How to create an auto-generated Date/timestamp field in a Play! / JPA? 졸리운_곰 2018.12.13 975
76 Spring Data repository with empty IN clause. 졸리운_곰 2018.11.16 237
75 Spring Data JPA Tutorial: Introduction to Query Methods 졸리운_곰 2018.11.16 266
74 JPA OrderColumn 에서의 정렬 order by 졸리운_곰 2018.11.16 720
» Jpa @elementcollection 의 데이터 정렬 @orderby : JPA - Using @OrderBy Annotation file 졸리운_곰 2018.11.16 877
72 Springboot 에서 Querydsl 사용하기 졸리운_곰 2018.09.18 283
71 Springboot 에서 DATA-JPA(Hibernate) 사용하기[3] - JOIN file 졸리운_곰 2018.09.18 185
70 Springboot 에서 DATA-JPA(Hibernate) 사용하기[2] - Entity, Repository, CRUD file 졸리운_곰 2018.09.18 259
69 Springboot 에서 DATA-JPA(Hibernate) 사용하기[1] - 기초 설정 졸리운_곰 2018.09.18 319
68 JPA_Mini_Book 이북 Java JPA file 졸리운_곰 2018.08.27 218
67 [Mybatis] parameterType="String" 사용시 문제점 졸리운_곰 2018.08.22 1510
66 MyBatis 에서 출력하는 에러 보기 : Catch exception in MyBatis 졸리운_곰 2018.08.22 354
65 MyBatis 기본 - insert,delete,update 졸리운_곰 2018.08.22 165
64 %Like% Query in spring JpaRepository 졸리운_곰 2018.08.20 189
63 Spring Data JPA Tutorial: Creating Database Queries From Method Names 졸리운_곰 2018.08.20 245
62 Spring Data JPA 에서 Java8 Date-Time(JSR-310) 사용하기 file 졸리운_곰 2018.05.28 257
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED