1

I am trying to develop a JavaFX Desktop application with Hibernate. In my data-model I have two entities (Player, Team). Every Player belongs to one Team.

Player

id : int firstName : String lastName : String ref_Team : int

Team

id : int Name : String

In my application I have currently two tables for each Entity and everything works well. But now I want to got a step further and in the TableView for Team-Entity I intend to add a column "Players Count".

I know how to bind a TableColumn, e.g. firstNameCol.setCellValueFactory((data) -> data.getValue().firstNameProperty());

But in my Team-Entity there is no property for counting the Players. Any ideas how to bind the numberOfPlayerCol?

1 Answer 1

2

Assuming you have an ObservableList<Player> with all the players, you can do something like

ObservableList<Player> allPlayers = ... ;

TableView<Team> table = new TableView<>();

TableColumn<Team, Number> playerCountCol = new TableColumn<>("Players count");
playerCountCol.setCellValueFactory(cellData -> 
    Bindings.createLongBinding(() -> 
        allPlayers.stream()
        .filter(player -> player.getTeamId() == cellData.getValue().getId())
        .collect(Collectors.counting()),
        allPlayers));

This is a fairly brute force approach which just counts everything whenever it needs. If you run into performance issues, you may need to do something more sophisticated. This should work for modest sizes of data set, though.

Here's a link to a quick example (the Player here has a direct reference to the Team, instead of a field matching its id, but the idea is the same).

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer. Thank you James!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.