Hibernate JPA @SortComparator Example
@SortComparator
The @SortComparator annotation is used to specify a Comparator for sorting the Set/Map in-memory.SortComparator Specifies in-memory Set/Map sorting using a specified Comparator for sorting. NOTE : Sorting is different than ordering (see OrderBy) which is applied during the SQL SELECT. For sorting based on natural sort order, use SortNatural instead. It is illegal to combine SortComparator and SortNatural.
Unidirectional custom comparator sorted set
@Entity(name = "Person")public static class Person {
@Id
private Long id;
@OneToMany(cascade = CascadeType.ALL)
@SortComparator(ReverseComparator.class)
private SortedSet<Phone> phones = new TreeSet<>();
//Getters and setters are omitted for brevity
}
public static class ReverseComparator implements Comparator<Phone> {
@Override
public int compare(Phone o1, Phone o2) {
return o2.compareTo( o1 );
}
}
@Entity(name = "Phone")
public static class Phone implements Comparable<Phone> {
@Id
private Long id;
private String type;
@NaturalId
@Column(name = "`number`")
private String number;
//Getters and setters are omitted for brevity
@Override
public int compareTo(Phone o) {
return number.compareTo( o.getNumber() );
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Phone phone = (Phone) o;
return Objects.equals( number, phone.number );
}
@Override
public int hashCode() {
return Objects.hash( number );
}
}
Bidirectional sorted sets
The @SortNatural and @SortComparator work the same for bidirectional sorted sets too:Example : Bidirectional natural sorted set
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL)@SortNatural
private SortedSet<Phone> phones = new TreeSet<>();
@SortComparator(ReverseComparator.class)
private SortedSet<Phone> phones = new TreeSet<>();
Before v6, @SortNatural must be used if collection element’s natural ordering is relied upon for sorting. Starting from v6, we can omit @SortNatural as it will take effect by default.
Comments
Post a Comment