如何在JavaEE中使用JDBC? [英] How to use JDBC in JavaEE?

查看:248
本文介绍了如何在JavaEE中使用JDBC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在JavaEE环境(weblogic 12)中进行开发,并且我的部分代码使用JDBC.因此,我需要从应用程序服务器获得JDBC连接.
我知道在JavaEE中使用JDBC确实是一个坏习惯,但这是我无法更改的代码(旧版).

I'm developing in a JavaEE environment (weblogic 12), and part of my code uses JDBC; Therefore, I need to aqcuire a JDBC connection from the application server.
I know it's a really bad practice to use JDBC in JavaEE, but that's a code I cannot change (legacy).

我找到了一种方法,但是我不确定这是正确的方法:

I've found a way to do it, but I'm not sure it's the right way:

@Resource(mappedName="mydsjndipath")
private DataSource ds;

public void foo() {
    Connection conn = ds.getConnection();
}

问题是我该如何处理最后的连接?
我不能真正提交/回滚它,因为我使用的是分布式事务.但是我至少应该关闭它吗?
而且,JTA事务会始终影响连接(在提交/回滚时)吗?

The question is what do I do with the connection at the end?
I can't really commit/rollback it, because I use a distributed transaction. But should I at least close it?
And will the JTA transaction will always effect the connection (on commit/rollback)?

或者也许还有另一种在JavaEE中使用JDBC的更好方法? (不,EntityManager的本机查询不会执行)

Or maybe there's another better way to use JDBC in JavaEE? (no, the EntityManager's native queries won't do)

推荐答案

为什么使用JDBC应该是不好的做法?

Why should using JDBC be bad practice?

如果您的应用程序服务器支持JDBC,而您让他通过JDBC I连接到数据库,我自己也看不出为什么您也不应在应用程序中使用它!?

If your application server supports JDBC and you let him connect to a DB via JDBC I, for myself, see no reason why you shouldn't use it in your application, too!?

另一种方法是在应用程序中手动加载驱动程序并从中获得连接.但这就像重新发明轮子!

Another approach would be to load the driver manually in your application and get a connection from it. But this would be like reinventing the wheel!

您也忽略了

  • JDBC连接池的服务器端管理
  • 此连接的可重用性

最后,您应始终关闭 Connection/Statement/ResultSet ,例如:

At the end you should always close your Connection/Statement/ResultSet like:

try {
  // your stuff here
}
finally {
  if(connection != null) {
    connection.close();
  }
  // same for statement/ResultSet ift not used anymore
}

这篇关于如何在JavaEE中使用JDBC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆