Skip to content

Instantly share code, notes, and snippets.

@hseritt
Created June 27, 2016 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hseritt/01e3479580e6cd4787e518d304a0cab9 to your computer and use it in GitHub Desktop.
Save hseritt/01e3479580e6cd4787e518d304a0cab9 to your computer and use it in GitHub Desktop.
How to handle opening and closing Hibernate sessions
Session session = HibernateUtil.getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
ManagedSessionContext.bind(session);
session.beginTransaction();
Query getAgentsQuery = session.createQuery(" from AgentModel where active=true");
@SuppressWarnings("unchecked")
List<AgentModel> agentList = getAgentsQuery.list();
for (AgentModel agentModel : agentList) {
log.info("Instantiating agent " + agentModel.getName() + " using class: " + agentModel.getClassName());
AbstractApplicationContext agentContext = new ClassPathXmlApplicationContext("agents-context.xml");
Agent agent = (Agent) agentContext.getBean(agentModel.getClassName());
if (runThreaded.equals("true"))
agent.start();
else
agent.run();
agentContext.registerShutdownHook();
agentContext.close();
}
ManagedSessionContext.unbind(HibernateUtil.getSessionFactory());
session.flush();
session.getTransaction().commit();
session.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment