I want to close statement automatically - java

I want to close statements automatically.
I want to achieve it using the technology of the following packages:
Java 1.5
Spring framework 2.5
It seems not to close statements automatically in the default settings, though I think that the transaction manager of Spring automatically shuts statements.
I do not want to call close() of statement as much as possible in the method for maintainability.
Is there a method to ensure that the statement's closed?
The amount of coding increases if coming for all the methods to have to call close() of statement, and there is a problem that the possibility that the omission is generated goes out.
Moreover, I am making the framework. It wants to make the restriction as much as possible by such a reason and to make a little method.
Moreover, is there an official site or document that shows the reason when there is no closing method?
I'm Japanese, so please explain using simple statements.

I believe Spring will handle all this for you if you use the SimpleJdbcTemplate. I'd recommend it highly.
The Spring transaction manager is not closing the statement. That's a separate concern. After all, you'd still want the statement closed even if you didn't have an open transaction.
I would not write your own framework. I would bet that you'd be hard-pressed to improve on what Spring 2.5 is already giving you. Perhaps it's more a matter of training and understanding Spring's capabilities better.

Related

How to get rid of database dependency of an already developed application having Oracle native queries?

I have an application with a huge code base which uses an Oracle database. I want to develop an hibernate app which can interact with incoming and outgoing request from the above said application without any dependencies of database.
Like if I want to change the database to mysql or postgresql it would not have any problem. Is this practical? Can it be done? Asking for help.
As to practicality, very seldom does an app ever change databases. While the idea sounds great it isn't often done and generally the benefits you can get from using built in database features sometimes outweighs the work of keeping it database independent.
As to it being done, it certainly can between SQL databases. To go from SQL to noSQL is a bit more tricky as they are in the process of supporting them in JPA. If interested in that take a look at Hibernate OGM. If you want to truly keep it so you can easily switch databases you need to stick to the JPA standard. See this on generating JPA compliant entities from the database. So long as you use ONLY JPA you can easily switch between the databases that provide a JPA implementation. Then you just include the correct implementation set the dialect and you are switched.
If you have access to change the current application it will probably be easier to just update each of the actions that contain the hard coded queries with your JPA code. If you have unit testing that would make this process much easier as well.
If you want to write something new, but not change the front end, you would need to handle whatever actions your forms on the front end are submitting. Making sure to make them available at the same path and with the same HTTP methods (GET, POST, PUT, etc.), that take the same parameters, and returning the same structure as what your actions due today.
Both approaches would allow you to go action by action replacing them. With writing something new though, replacing them one at a time is a little more difficult if both the new app and old app aren't in the same domain OR if authentication/authorization is involved.
Good luck and best wishes!

JDBC - SQL statements execution time logging

I need to log the SQL execution times in my Java EE application (Any further statistics would be an optional bonus).
Things are setup in a more-less standard way: Datasource on Application server serving pooled JDBC connections.
Application uses for DB access mix of:
Hibernate and
Spring JDBCTemplate
It runs on:
Glassfish OSE and
Oracle DBS
I know about: Anything better than P6Spy? however the question/answers are outdated, from my point of view.
What I've found so far:
I could go for the pure Hibernate approach (hibernate show query execution time)
but it's not feasible due to mixed DB access in my case
I could use some of the custom JDBC drivers
p6spy - however project seems couple years dead (last commit 3 years ago: http://sourceforge.net/p/p6spy/code/23/tree/trunk/)
log4jdbc - however no release for more than 1 year, and source activity seems to be cca 6 months not touched (http://code.google.com/p/log4jdbc/source/list)
another 2: log4jdbc-log4j2 and log4jdbc-remix - which seem alive, but I'm not sure about stability and broad usage
Recommendations based on experiences are very welcome.
Please note, I'm interested in kind of answers like: We're using XYZ and this is our experience, rather than I googled just now and feel like...
If you want dead accurate SQL execution time then best option is sql trace. But you want to put it in your Java EE application, so obviously want a somewhat accurate execution time.
Following are the things i would suggest [I have implemented them in my code]:
If you just want it for loggin purpose then have appropriate Log4j debug messages which wil l print time along with log entry.
I implemented a BatchLog table for my application which use to record start and end time of the operation. So in your case it will be start and end time of your query. Now if it is just a single query then probably triggers might help here or else you can update log table just before and after running query. Or even better will be a stored procedure which can take care of whole thing and give more accurate data.
Measuring time and logging it seems like a job for AOP. If you are using EJB, a simple interceptor should solve your problem(for example http://www.javacodegeeks.com/2013/07/java-ee-ejb-interceptors-tutorial-and-example.html). If its Spring(judging from JDBCTemplate), try Aspectj.
OK, thanks a lot for your answers.
Finally I decided to go for the P6Spy with patches specific to our scenario.
Moreover, as I believe that the gap P6spy is filling still exists these days, I decided to participate in it's development (https://github.com/p6spy/p6spy). Feel free to report your issues or feature requests to: https://github.com/p6spy/p6spy/issues to make it fit your needs.

Spring Transactions to ensure consistency across 2 REST services?

I have 2 REST apis where I "persist" data, in a "transaction". I'm curious to hear suggestions on how to ensure that if the 2nd one has trouble the first one could be "rolled back".
I currently have a retry loop and if that fails I send a delete to the first call.
It works fine, I was just curious if it is possible to use spring transactions to handle this.
For that matter, are there other options?
It would be very interesting and useful if something like this was possible, but I don't think it could be possible since there is no standard API for commits/rollbacks with REST APIs as there is with the JDBC API. With Spring, you could never simply mark a method as #Transactional since Spring would have no idea how to "roll back" anything you did over a REST call without having to explicitly state it.

Need help figuring out a lightweight Java EE framework

We have an old and big Java EE project, where at some places due to bad coding database connections has not been closed properly/or not cleaned up in catch/finally block.
We have limited our database connection pool to 100 connections. Sometimes it happens that the connection remains open and all the 100 connections are used, so the application gets hanged up. I'm trying to restructure this project, obviously I'll take care of this bad code when I get there, I'm wondering is there any lightweight Java EE framework which closes this opened db connection automatically without writing conn.close() or session.close().
Maybe something like Django where every db connection are closed at the end of every request/reposnse cycle.
I do know that I can use tools like p6spy and IronTrack SQL to look for statements that fail to close, but I'm more interested in frameworks as this project doesn't use any and I'm trying to integrate this project with a framework.
There is try-with-resource in Java 7 that may help.
Take a look
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html
Here Java 7 Automatic Resource Management JDBC (try-with-resources statement) you can similar question.
Check for detecting connection leak. I am sure, you will find some tools for this.
I think you should go through a couple different frameworks, demos should be available if you search for them and choose the one which most fits your current and near future needs. I personally like Primefaces/Hibernate (if you're in JSF).
The lightweight approach in Java EE is to use simple POJO based beans called EJBs that do the DB work.
With them, in many or all cases, the DB connection is a thing that's completely handled for you behind the covers by the server.
For instance (assuming your queries for now are native SQL):
#Stateless
public class MyBean {
#PersistenceContext
private EntityManager entityManager;
public void doDBWork() {
entityManager.createNativeQuery("update foo set a = 1").executeUpdate();
}
}
In this example when you call doDBWork a transaction automatically starts and it ends when you leave that method. Somewhere in between a connection is retrieved from the connection pool and returned to it. The code is automatically totally safe in the face of exceptions or concurrent access.

Execute a sql statement when a connection is created

For our application to work properly we need to execute a SQL Statement on every new connection, before that connection is handed out to the application.
How do I configure a data source in WAS 7 accordingly?
We found the (deprecated) option to validate the datasource using a sql statement, which hopefully does the trick (coworker is testing it right now). This sounds wrong, since we are not 'testing' the connection, but setting it up properly. Also its deprecated so this probably will stop working with future versions of websphere
Is there a clean and correct way to do this?
The statement we'd like to execute is
ALTER SESSION NLS_SORT='GERMAN_AI'
One alternative approache: The application is hibernate based, so if we could convince hibernate to execute the statement before using a connection, this would work as well.
If it were me, I would just use the "connection test" approach:
It works!
The YAGNI principle says "worry about deprecation when it happens... if it ever happens" - probably years away or never
You will not add any business value by finding the "correct" way
You can drop this and get on with some real work that actually adds value to your project
The only downside is that it will be executed every time a connection is tested, which may be many times during the life of the connection, but so what - it's a very fast executing statement and is idempotent, so no problem.
Not a WAS expert by any means, but if you can set up Tomcat JDBC to provide your database connection pooling, it has a parameter amongst others called "initSQL". You can set that to a SQL statement that you want the connection pool to run whenever a connection is created.
Tomcat JDBC Connection Pool
A.
One way to go would be to use a custom Hibernate dialect, since you are actually specifying a 'different' way to talk with the database. I have no idea where to add the initialization code though.

Categories

Resources