Hi, I have just finished the book (Hibernate in action), and it was
great!
One chapter that I liked most was the one about DAO patterns.
Anyway, the DAO pattern is for j2ee as said in the book.
But can you use it in standalone j2se java applications as well?
The reason I am asking is because in the book the DAO methods
don't close the sessions.
I think that the HibernateUtil class is made to do it automatically,
correct me if I am wrong.
Can I copy everything as the book including
HibernateUtil and letting HibernateUtil close the session without worrying about it ,for j2se or not?
Here below is my code for the CustomerDAO class that I have just
implemented.
It is meant to retrieve a customer given the phone number.
Here I am closing the session.
Code:
public Customer getCustomer(String phone) throws Exception {
Transaction tx = null;
Session session = null;
try{
session = HibernateSession.currentSession();
tx = session.beginTransaction();
Iterator iter = session.iterate("from Customer customer order by customer");
while(iter.hasNext()){
Customer customer = (Customer)iter.next();
if(customer.getPhone().equals(phone)){
return customer;
}
}
tx.commit();
}
catch (Exception e) {
if(tx != null) {
try{
tx.rollback();
}
catch(Exception he){
he.printStackTrace();
throw e;
}
}
throw e;
}
finally{
try{
session.close();
}
catch(Exception es){
throw es;
}
}
throw new Exception();
}
So two questions , I repeat.
1) Can I copy the HibernateUtil, UserDAO (and the other related classes)
idea straight to a j2se application and leaving the closing of a session
for the HibernateUtil class.
2) The customer method is that I have provided with this mail, is that a
correct way of doing it safely?
In case I don't want to use the HibernateUtil idea, depending on the
different scenarios that I may encounter.
Thanks for any help!