0

Our application uses PagingAndSortingRepository to serve our REST API. This works great, but we ran into a specific edge case that we can't seem to solve: We have a alphanumeric field that has to be sortable (e.g. SOMETHING-123). One possible solution was to use something like a regex inside the database query's order by. This was ruled out, as we wanted to stay database independant. Thus we split up the column into two columns.

So before we had an Entity with 1 String field:

@Entity
public class TestingEntity {
    @Id
    @GeneratedValue
    private long id;

    private String alphanumeric
}

And now we have an Entity with 2 additional fields and the old field made @Transient which is filled at @PostLoad:

@Entity
public class Testing {
    @Id
    @GeneratedValue
    private long id;

    @Transient
    public String alphanumeric;

    @PostLoad
    public void postLoad(){
        this.alphanumeric = this.alphabetic + "-" + this.numeric;
    }

    public void setAlphanumeric(String alphanumeric) {
        int index = alphanumeric.indexOf("-");
        this.alphabetic = alphanumeric.substring(0, index);
        this.numeric = Long.parseLong(alphanumeric.substring(index + 1));
    }

    @JsonIgnore
    private String alphabetic;

    @JsonIgnore
    private Long numeric;

}

This is working great and the additional fields do not get exposed. However the sorting on the field "alphanumeric" does obviously not work anymore. The simplest solution would be to make this request:

localhost:8080/api/testingEntity?sort=alphanumeric,asc

and internally rewrite it to the working request:

localhost:8080/api/testingEntity?sort=alphabetic,asc&sort=numeric,asc

What is the best way to tackle this issue?

wederer
  • 550
  • 2
  • 5
  • 17
  • Have you tried an Url Rewrite Filter? https://stackoverflow.com/questions/30476586/how-can-i-add-urlrewritefilter-in-spring-boot – Jens Schauder Jun 25 '18 at 08:50
  • @JensSchauder No, I will look into it. Thank you! – wederer Jun 25 '18 at 10:05
  • Another option would be a database view mapped to the entity using `@SecondaryTable`. `alphanumeric` is then no longer a transient field but a read-only database column that can be sorted and queried as any other field. – Alan Hay Jun 26 '18 at 08:26
  • @AlanHay This however is worse performance wise, isn't it? – wederer Jun 26 '18 at 18:10

0 Answers0