常见的数据库/ dao方法应该是静态的吗?

mem*_*und 4 java static design-patterns hibernate

我有一个方法,在我的代码中使用3-4次来自不同的位置.通常我会为此引入静态实用方法,我也这样做了.

但我想知道这是一个好习惯,如果这个静态方法执行一些数据库/ dao逻辑?将以下内容作为伪代码示例:

class DaoUtiliy {

    public static void updateToDB(List a, List b) {
        Dao dao = new Dao();
        dao.open(); //begin transaction     

        //create some variables using the list a, that are used to fetch the db entry:
        String time, String date; //some more
        Entity entity = dao.find(time, date);

        //update anything in that entity;
        entity.setProperty(b.get(0));

        dao.close(); //commit transaction
    }   
}
Run Code Online (Sandbox Code Playgroud)

你也会把它放在静态方法中吗?或者更确切地说,new DaoService().updateToDB(a, b);从需要的地方创建一个anc调用方法?

Ash*_*wal 5

我更喜欢DAO中的非静态方法,原因如下

  1. 使它们非静态可以更容易使用像Spring这样的框架注入值
  2. 编写单元测试用例对于静态方法并不容易,因为它们无法被覆盖
  3. 此外,如果您想扩展DAO的功能,则无法覆盖静态方法.