如何将 jdbcdaosupport 集成到 spring mvc3

发布于 2024-12-12 06:49:06 字数 472 浏览 3 评论 0原文

我在我的应用程序中使用spring mvc3,并且在dao层中我想使用jdbctemplate,但是我不知道在控制器中的哪里添加dao?

例如:

@Controller
public class UserController{
  private UserDao udao;
  public String list(Model model){
    udao=new UserDaoImple();
    List<User> users=udao.list();
    model.addAttrubut('users',users);
    return "list";
  }
}

上面的代码只是一个例子,我想知道在哪里创建userdao?

另外,由于我想使用jdbctemplate,并且建议为一个数据源只创建一次jdbctemplate,那么如何让所有daos使用相同的jdbctemplate呢?

I am using the spring mvc3 in my applicatio,and in the dao layer I want to use jdbctemplate,however I do not know where to add the dao,in the controller?

For example:

@Controller
public class UserController{
  private UserDao udao;
  public String list(Model model){
    udao=new UserDaoImple();
    List<User> users=udao.list();
    model.addAttrubut('users',users);
    return "list";
  }
}

The above code is just an example,I want to know where to create the userdao?

Also,since I want to use the jdbctemplate,and it is recommended that the jdbctemplate is created only once for one datasourece,so how to make all the daos use the same jdbctemplate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝海似她心 2024-12-19 06:49:07

您可以使用 Spring IOC(依赖注入)像这样注入 DAO

@Autowired
UserDao userdao;

,或者您可以使用存储库模式,并为所有 DAO 创建一个中心点,这样您只需转到存储库并请求您需要的 DAO。

为此,您必须创建具有所有 DAO 的所有实例的单例类,并且当被要求时为您的类提供一个实例,因此您不需要实例化 Dao,只需执行一个

Repo.getUserDaoInstance();

在我看来,请采用 Spring 方法将学习一项非常有用的技能,并且当您知道自己在做什么时,维护起来会容易得多。

You could use Spring IOC (dependency injection) to inject the DAO like this

@Autowired
UserDao userdao;

or you could use the repository pattern, and create a central point for all the DAOs so you just go to the repository and ask for the DAO you need.

for that you would have to create singleton class that has all instances of all DAOs and when asked give give an instance to your class, so you don't need to instantiate the Dao just do a

Repo.getUserDaoInstance();

In my opinion, go for the Spring approach you will learn a very useful skill and it's a lot easier to maintain when you know what you are doing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文