Skip to content
Advertisement

SortedSet + Hibernate’s @SortNatural + Comparable not sorting elements when fetch from DB

I know similar questions have been asked before, I looked through them but still can’t figure out why in particulary this case sorting is not working. I have 2 Entities – Category and Transaction with relations OneToMany. Inside one category there can be many transactions and One transaction belongs to certain category. When I fetch the category from DB I want all related transactions to be fetch in sorted order – for that I am using SortedSet as interface of the collection of TXs and TreeSet as implementation – this should tell Hibernate to use proper data structure. Also I am using @SortNatural HIbernate’s annotation and offcourse Transaction entity implements Comparable – to define the sorting order (sorting by Long ID in natural order). NB – equals & hashcode are NOT overriden as it not required by definition of TreeSet. For some reason when I fetch the Category and its transactions on front-end – they are displayed in “random” order every time I refresh the page. PLease advise what is wrong here. I referred to Hibernate docs regarding SortedSet – please see the link Hibernate SortedSet

@Entity
@Table(name = "category")
public class Category implements Comparable<Category> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "bedget")
    private BigDecimal budget;

    @Column(name = "name")
    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "groupp_id")
    private Group groupp;

    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "category")
    @SortNatural
    private SortedSet<Transaction> transactions = new TreeSet<>();

//getters - setters

@Entity
@Table(name = "transaction")
public class Transaction implements Comparable<Transaction>{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;

    @Column(name = "total")
    private BigDecimal total;

    @Column(name = "type")
    private String type;

    @Column(name = "note")
    private String note;

    @ManyToOne
    @JoinColumn(name = "category_id")
    private Category category;

// getters-setters

 @Override
    public int compareTo(Transaction o) {
        return Long.compare(this.id, o.id);
    }

Advertisement

Answer

Problem solved. Found that SortedSet was wrapped into Unmodifiable Set in busness layer during results filtering (stream) and Unmodifiable Set doesn’t preserve iteration order.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement