How to use JDBC in JavaEE?

隐身守侯 提交于 2019-12-07 18:50:11

问题


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();
}

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)?

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


回答1:


Why should using JDBC be bad practice?

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!

Also you dismiss the advantage of

  • the server side management of your JDBC connection-pool
  • the reusability of this connection

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
}



回答2:


close the connection- conn.close();



来源:https://stackoverflow.com/questions/9767694/how-to-use-jdbc-in-javaee

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!