首页 > 解决方案 > 如何使用 MySQL 连接器添加回调方法?

问题描述

我有一个存储库类,我在其中使用 MySQL Connector for Java 从我的数据库执行查询。

该方法在后台线程上运行,使用

new Thread(() -> {
     ...perform query
}).start();
public class CustomerRepository {

private ObservableList<Country> listCountries = FXCollections.observableArrayList();


public ObservableList<Country> getCountries() {
        new Thread(() -> {
            Statement statement = null;
            ResultSet resultSet = null;

            try {
                statement = ConnectionManager.getConnection().createStatement();
                resultSet = statement.executeQuery(Constants.QUERY_GET_COUNTRIES);
                while (resultSet.next()) {
                    int countryId = resultSet.getInt(Constants.TABLE_COUNTRIES_COL_COUNTRYID);
                    String country = resultSet.getString(Constants.TABLE_COUNTRIES_COL_COUNTRY);
                    String createDate = resultSet.getString(Constants.TABLE_COUNTRIES_COL_CREATEDATE);
                    String lastUpdate = resultSet.getString(Constants.TABLE_COUNTRIES_COL_LASTUPDATE);

                    Country countryObj = new Country(countryId, country, createDate, lastUpdate);
                    this.listCountries.add(countryObj);
                }

            } catch (SQLException e) {
                System.out.println("Query Countries: " + e.getMessage());
            } finally {
                ConnectionManager.closeResultSetAndStatement(resultSet, statement);
            }
        }).start();
    }

}

此代码引发Missing return statement错误,因为我不知道如何返回实例变量listCountries

我将如何使用回调方法而不是new Thread(() -> {...返回列表?原因是如果我不使用新线程,UI 将在执行查询时冻结。

标签: java

解决方案


推荐阅读