I'm trying to build a small Swing application to learn Hibernate, but all samples I found in the web are related to Hibernate use with web applications.
So I need some guidelines to move forward.
I understand that I need a static SessionFactory, but what about Session ?
I had a look at the code provided by nvolpini in the page:
http://forum.hibernate.org/viewtopic.php?t=925108
and I have some doubts.
1) From these two methods:
Code:
public User selectAndClose(int id) throws HibernateException {
User res = null;
Session session = null;
try {
session = factory.openSession();
res = (User) session.load(User.class, new Integer(id));
} catch (net.sf.hibernate.ObjectNotFoundException h1) {
throw h1;
} catch (HibernateException h2) {
throw h2;
} finally {
factory.closeSession(session);
}
return res;
} //select(int)
public User select(int id) throws HibernateException {
User res = null;
Session session = null;
try {
session = factory.openSession();
res = (User) session.load(User.class, new Integer(id));
} catch (net.sf.hibernate.ObjectNotFoundException h1) {
throw h1;
} catch (HibernateException h2) {
throw h2;
}
return res;
} //select(int)
it seems that I should always open a session. Then I can close it at once (first method) or leave the session open (second method).
I suppose that the difference is that:
- in the first case I can access just the data of the retrieved User object
- in the second case, after the method returns the user object, I am able to browse the other objects that have some relationship with the User class. For example, I could do a: user.getGroups().
Is this correct ?
2) From this method:
[code] public User selectFull(int id) throws HibernateException {
Session session = null;
try {
session = factory.openSession();
User res = (User) session.load(User.class, new Integer(id));
//Inicializa os grupos
Hibernate.initialize( res.getGroups() );
//Inicializar as empresas
Hibernate.initialize( res.getCompanies() );
Iterator it = res.getGroups().iterator();
while (it.hasNext()) {
Group group = (Group) it.next();
//Inicializa as permiss