Created
June 27, 2016 02:16
-
-
Save hseritt/01e3479580e6cd4787e518d304a0cab9 to your computer and use it in GitHub Desktop.
How to handle opening and closing Hibernate sessions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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