首页 > 解决方案 > 无法在 Java 应用程序中实现 DAO 设计模式

问题描述

我是 Java 新手,我正在尝试设计一个应用程序,该应用程序具有从数据库getCountries()获取数据的方法,该方法通过搜索输入 ID 值findCountryByCode(int codeID)和最后,一种将新国家/地区保存到表中的方法称为saveCountry(Country countries)。我被要求在本练习中使用 OOP 和设计模式的所有良好实践。

我有几个类管理数据封装,但我在尝试调试一些输出错误时遇到了困难。连接到数据库MySqlCountryDAO的类建立了连接,但不仅没有在终端上返回任何表值,而是提示我“java.lang.NullPointerException”。我做了我的研究,但找不到为什么会出现这个错误。有人可以看看这门课并给我一个灯吗?这是连接到DataSource 类[即数据库连接器] 的类的代码。

public class MySqlCountryDAO implements CountryDAO {

DataSource db = SingletonInstance.getInstance();

/**
 * Returns an ArrayList of all the Countries in the database
 * @returns arrayList of country Objects
 */
@Override
public ArrayList<Country> getCountries() {

    ArrayList<Country> countries = new ArrayList<Country>();
    String query = "SELECT * FROM country"; // MySQL query
    ResultSet rs = db.select(query); // catch the ResultSet and place the result of the query in the result set

    int code = 0;
    String name = "";
    Continent continent = null;
    long surfaceArea = 0;
    String headOfState = "";
    Country c = null;

    // loop over the resultSet to fill ArrayList w results
    try {
        while (rs.next()) {
            code = rs.getInt(1); // don't quite get it why starts at 1
            name = rs.getString(2);
            continent = Continent.valueOf(rs.getString(3));
            surfaceArea = rs.getLong(4);
            headOfState = rs.getString(5);

            //builder pattern to be implemented here
            c = new Country(code, name, continent, surfaceArea, headOfState); //new instance of Country class
            countries.add(c);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return countries;
}

}}

主要课程:

public class Main{

public static void main (String[] args){
    /**
     * instance of the client connecting to the DataSource class
     */
    MySqlCountryDAO dao = new MySqlCountryDAO(); //instance of dao

    ArrayList<Country> countries = dao.getCountries();
    for (Country c : countries){
        System.out.println(c);
    }
}
}

下面是我运行代码时返回的输出。 SQL Exception: java.lang.NullPointerException Exception in thread "main" java.lang.NullPointerException at MySqlCountryDAO.getCountries(MySqlCountryDAO.java:28) at Main.main(Main.java:11)

我不知道是什么原因造成的,也不知道如何调试它。我还想在上面实现很多其他功能,但在主应用程序运行之前我无法测试它们。非常感谢您提供解决问题的意见,并欢迎提出改进程序结构的建议。

带有完整项目的 GitHub 链接在这里

太感谢了!

标签: javadesign-patternssingletondaobuilder

解决方案


推荐阅读