首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一个通用的数据库/dao方法应该是静态的吗?

一个通用的数据库/dao方法应该是静态的吗?
EN

Stack Overflow用户
提问于 2014-01-21 15:54:19
回答 1查看 2K关注 0票数 4

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

但是我想知道这是否是一个好的实践,如果这个静态方法执行某种数据库/数据逻辑?以以下为伪代码示例:

代码语言:javascript
复制
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
    }   
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-22 16:42:33

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

  1. 使它们成为非静态的,使使用Spring之类的框架更容易注入值
  2. 编写单元测试用例对于静态方法并不容易,因为它们不能被重写。
  3. 另外,如果您想扩展DAO的功能,则不可能覆盖静态方法。
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21262961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档