Hello,
How should I use hibernate properly from different threads ?
Main: (I'm getting new hibernateUtils and new authService here)
Code:
public class MainClass {
private static AuthService authService;
public static void main(String[] args) {
try (HibernateUtils hibernateUtils = new HibernateUtils()) {
init(hibernateUtils);
UserInterface userInterface = new SwingInterface(authService);
userInterface.run();
} finally {
}
}
private static void init(HibernateUtils hibernateUtils) {
AuthDAO authDAO = new HibernateAuthDAOImpl(hibernateUtils);
authService = new AuthServiceImpl(authDAO);
}
}
HibernateUtils:
Code:
public class HibernateUtils implements AutoCloseable {
private SessionFactory sessionFactory;
private Session session;
public HibernateUtils() {
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public Session getSession() {
if(session == null) {
session = sessionFactory.openSession();
}
return session;
}
@Override
public void close() {
sessionFactory.close();
}
}
SwingInterface, that makes 2nd thread
Code:
public class SwingInterface implements UserInterface {
private AuthService authService;
public SwingInterface(AuthService authService) {
this.authService = authService;
}
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new AuthWindow(authService);
}
});
}
}
SwingInterface makes 2nd thread for a window and if I call authService with hibernateUtils (that I've made in Main) I will get exception:
Code:
Exception in thread "AWT-EventQueue-0" org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
at [...].db.utils.HibernateUtils.getSession(HibernateUtils.java:24)
But if I create new hibernateUtils in that new thread - all goes well.
What should I do ? How to do it correctly... ? Thank you.