When reading from database, I want to sort my Post
entities based on two factors:
- likes count (the more the better)
- age (the newer the better)
Currently I have implemented it this way (as a calculated value):
@Entity
public class Post {
// divide timestamp by a day length so after each day score decrements by 1
@Formula("UNIX_TIMESTAMP(creation_date_time) / 24 * 60 * 60 * 1000 + likes_count")
private long score;
@CreationTimestamp
private LocalDateTime creationDateTime;
@Min(0)
private long likesCount;
}
It works fine but may not be the best approach because:
- I think the RDBMS cannot make any index for
score
attribute. - The hard-coded function
UNIX_TIMESTAMP()
is specific to MySQL. So this will cause problems if I want to use another database (say H2) in my test environment.