I have to create a company object in Java with a series of attributes. One of them is the size that comes to me in String and has this format
- 1-10
- 11-50
- 51-200
- 1000-5000
When making a query in the repository to return a list of companies ordered by size in ascending order, what it does is consider that 1000 goes before 11. I understand that since the second number is smaller than the second number of the second number , is the logic that works.
@Entity (name="company")
@Getter
@Setter
@ToString
``public class Company {
@Id
@Column(name = "id", nullable = false)
private String id;
private String website;
private String name;
@Digits(integer = 4, fraction = 0)
private Integer founded;
private String size;
private String locality;
private String region;
private String country;
private String industry;
@Column(name="linkedin_url")
private String linkedinUrl;
public Company(String id, String website, String name, Integer founded, String size, String locality, String region, String country, String industry, String linkedinUrl) {
this.id = id;
this.website = website;
this.name = name;
this.founded = founded;
this.size = size;
this.locality = locality;
this.region = region;
this.country = country;
this.industry = industry;
this.linkedinUrl = linkedinUrl;
}
public Company() {
}
}
@Query("select c from company c order by c.size")
List<Company> findByOrderBySizeAsc();
If what you need is to order by the first size of the
SIZE
, what you need is to obtain that first size as a single element.To do this you must:
In the case of SQLServer (for example) the first thing is done with the function
CHARINDEX
and the second with theSUBSTRING
. In your case you do not comment which DB Manager you use, but you should look for the equivalent ones.A query like this:
It should return the position of the "-" , and the string before it. Something like this:
From there, it's easy to get the aghora sort, just use the field with the "new" value
SIZE1
instead of the fieldSIZE
.In the case of MySQL , the search function is
LOCATE
, and itSUBSTRING
must start with 1. So you can try the followingSQL
:In the end I had to make a comparator. The code has been as follows: