zjffdu
zjffdu

Reputation: 28944

How to sort a table by its associated records number in another table in CRUD?

I have a Tag class which has a list of UserTags. In the admin page I can modify it to show how many UserTag are associated with each Tag, but how can I sort it by the number of UserTags it is associated with in the admin page? Thanks.

@Table(name = "UTS_TAG")
public class Tag extends GenericModel {
    public Long id;

    public String name;

    public String description;

    @Required
    public Date last_modified = new Date();

    @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL)
    public List<UserTag> userTags;
}

Upvotes: 1

Views: 187

Answers (1)

Pere Villega
Pere Villega

Reputation: 16439

You can create a new field and autopopulate it with the number of tags associated. Check the @Formula annotation for that (see this other answer).

Something like:

@Formula("SELECT COUNT(u.id) FROM UserTag u WHERE u.tag.id = id")
public long numberOfUserTags; 

Upvotes: 2

Related Questions