How to use JDBC in JavaEE?

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

I found a way to do this, but I'm not sure if this is the right way:

@Resource(mappedName="mydsjndipath") private DataSource ds; public void foo() { Connection conn = ds.getConnection(); } 

The question is, what should I do with the connection at the end?
I cannot really execute / rollback because I am using a distributed transaction. But should I at least close it?
And will the JTA transaction always work with the connection (when committing / rolling back)?

Or maybe there is another better way to use JDBC in JavaEE? (no, internal EntityManager requests will not be executed)

+2
source share
3 answers

I will try to answer it myself: p

I see that we all agree that the way to get JDBC Connection should be done using the DataSource dependency injection.

Attempting to call Connection.commit or Connection.rollback will result in an error (at least in Weblogic 12), so you don't have to bother with this.

If the connection closes at the end of use, calling Connection.close ? Yes.
This intro will not commit or roll back the connection, but it will prevent any use of it.

So how do we make or roll back a connection?
This is done by the application manager when the JTA transaction containing the connection is committed or rolled back.

-1
source

Why should using JDBC be bad practice?

If your application server supports JDBC, and you allow it to connect to the database via JDBC I, for me I see no reason why you should not use it in your application !?

Another approach would be to manually load the driver into your application and get a connection from it. But it will be like rethinking the wheel!

You are also missing an edge.

  • server-side management of your JDBC connection pool
  • reuse of this compound

In the end, you should always close your Connection / Statement / ResultSet, for example:

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

close connection- conn.close ();

0
source

Source: https://habr.com/ru/post/948628/


All Articles