How to use JDBC in JavaEE?

2019-05-18 18:14发布

问题:

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



标签: java-ee jdbc jta