I am current working on a project which was built with Struts and Hibernate .
All DAO classes in the project has the following code
Inside constructor:
hibernateSession = HibernateUtil.currentSession();
tx=hibernateSession.beginTransaction();
Inside finally clause of all methods:
HibernateUtil.closeSession();
What this effectively means is that, in my business code, I have to initialize the reference variable or create an anonymous object every time I want to access data from the database, i.e.
If I have to access method1
and method2
of class A
:
A a= new A();
a.method1(); // access method 1
a = new A();
a.method2(); //access method 2
I now mostly use anonymous objects to get this done ie
new A().method1(); //access method 1
new A().method2(); //access method 2
Now my questions are:
Are anonymous objects garbage collected just after usage? In my project, since every access to methods in DAO class is via anonymous object, will it adversely affect the memory footprint ? if yes any alternative way?
Am I doing it correctly or is there a better way?
Is this the best/correct way of implementation using Hibernate?
Is my usage of the term "anonymous object" for
new A();
correct? While searching for the same in Google , I noticed many comments saying this is not called anonymous object in Java, but also came across some articles explaining this as anonymous objects.