kpenrose
kpenrose

Reputation: 186

JavaFX, tableview and database tables

I am currently using JavaFX to display data from a SQL Server database. I have created a TableView based on the contents of one table in the database. The database table is a collection of Products, so the TableView declaration is:

@FXML
private TableView<Products> productTable;

And each row in the TableView is declared something like this:

@FXML
private TableColumn<Products, String> productName;

Each column has a ValueFactory which contains a PropertyValueFactory which maps the data from the database to the column. Now what I'd really like to do is have my table contain data from 2 database tables, since there is a one-to-one relationship between the product and a cost table. However, I haven't found a clever way to do this yet.

Anyone have any suggestions or idea?

Upvotes: 3

Views: 3276

Answers (2)

scottb
scottb

Reputation: 10084

Another solution that may be applicable to your problem is to combine the data from the two tables into a JDBC connected RowSet object, and then use the jdbcRowSet object as source of data for your TableView. You can easily write an SQL query that could combine the data from both tables that you need into one rowset object.

Instead of mapping data from the database to the TableView, you'd map from the rowset object to the TableView. Naturally, this solution is available to you only if you are able to execute SQL queries against the database yourself. If you are limited to accessing the database through a data access object or other CRUD methods, then this won't work for your case.

Upvotes: 1

Uluk Biy
Uluk Biy

Reputation: 49215

You can write custom cell value factory, if you already defined relationships of the Products model to those table models. In the code below, the "Cost and Model of the product" column uses 2 related table models to render its cells, which are Cost and Model.

TableColumn<Person, String> costAndModelCol = new TableColumn<Person, String>("Cost and Model of the product");
costAndModelCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person, String>, ObservableValue<String>>() {
    public ObservableValue<String> call(TableColumn.CellDataFeatures<Person, String> p) {
        return SimpleStringProperty(p.getValue().getCost().getValue() + " (model: "+ p.getValue().getModel().getYear() +")");
    }
});

Upvotes: 2

Related Questions