关于必须在DB上执行某些查询的非常简单的Java命令行应用程序的体系结构的一些疑问

时间:2015-02-16 11:08:43

标签: java java-ee jdbc architecture

我在JDBC和架构设计方面都很陌生。

我必须实现这个简单的控制台应用程序(它是一个运行在Windows命令提示符下的命令行应用程序)。

我的应用程序由类组成,其中包含 main()方法。此 main()方法接收2个参数(用户在执行应用程序时插入)并使用这些参数在数据库上执行查询。

所以我正在学习本教程:http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm

好的,所以我做了类似的事情:

public class Main {

    public static void main(String[] args) {

         Properties prop = new Properties();
         InputStream input = null;

         if(args.length != 0) {
            String partitaIVA = args[0];
            String nomePDF = args[1];
         }

         Connection conn = null;
         Statement stmt = null;

         try {
             ....................................................
             ....................................................
             ....................................................

             Class.forName ("oracle.jdbc.OracleDriver");

             TimeZone timeZone = TimeZone.getTimeZone("Etc/GMT+2");
             TimeZone.setDefault(timeZone);

             conn = DriverManager.getConnection(prop.getProperty("dburl"), prop.getProperty("dbuser"), prop.getProperty("dbpswd")); // Oracle DB

} catch(SQLException ex) {
             ex.printStackTrace();
         } catch (ClassNotFoundException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         } catch (FileNotFoundException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         } catch (IOException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         } catch (URISyntaxException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         }
    }
}

所以在这个阶段我只注册了Oracle DBMS的JDBC驱动程序,然后通过这一行获得了连接:

conn = DriverManager.getConnection(prop.getProperty("dburl"), prop.getProperty("dbuser"), prop.getProperty("dbpswd")); // Oracle DB

效果很好,并且正确获取连接对象。

好的,看看发布的tuotorial,它表明,在获得初始化的 Connection 对象后,他使用此连接创建一个 Statement 对象代表要执行的SQL语句(使用表示查询的String),然后执行此SQL语句获取 ResultSet ,以便最后迭代此 ResultSet 对象以提取表示结果的所有行执行查询。

我很清楚,但我认为将所有这些内容放在我的 Main 类中是非常糟糕的。

所以我想我可以用以下方式分开:

  1. 进入 Main 类的 main()方法,我获取连接(此时已完成)。

  2. 然后我做了一个 DAO 类,我做了所有其他操作:创建 Statement 对象以及相关查询,查询执行和提取将 ResultSet 值添加到集合中。

  3. 首先我进入 main()方法获取连接,然后创建 DAO 对象,将此连接传递给它,这样我就可以执行查询了。 / p>

    从架构的角度来看,这是一个有效的解决方案吗?

1 个答案:

答案 0 :(得分:0)

是的,有效的主要类是你的UI层。 Multi-Layer Architecture将数据访问与UI层分开。

现在,对于单个类“应用程序”,我不确定是否会烦恼,因为多层架构的重点在于分离问题,从而简化应用程序。

如果您发现自己正在编写第二个接口,添加重要的业务逻辑,或者进行多个查询,那么您应该考虑在其中添加更多结构。