In answer to my own question:
Inject HibernateSessionSource and call its create() method to get a new
session.
public synchronized void execute(String url, String subject,
SendEmail sendEmail, HibernateSessionSource sessionSource) {
// For each mailout fetch url and send mailout
logger.debug("BulkEmailerImpl.execute was called
--------------------------------");
Session session = sessionSource.create();
userDAO = new UserDAOImpl(session);
I just need to find a better way of instantiating the DAO.
Regards,
Greg
-------- Original Message --------
Subject: Reusing tapestry hibernate session in a thread
Date: Sun, 29 Jan 2012 11:28:41 +1000
From: Greg Pagendam-Turner <g...@liftyourgame.com>
Organization: Liftyourgame
To: Tapestry users scheduled thread <users@tapestry.apache.org>
Hi,
I have a batch job that sends email to users based on a query in my
database.
AppModule starts it up like so in a:
@Startup
public static void scheduleJobs(PeriodicExecutor executor, final
BulkEmailer emailer,
@Value("${liftyourgame.url}")
String urlIn,
@Value("${liftyourgame.subject}")
String subjectIn,
final SendEmail sendEmail
) {
final String url = urlIn;
final String subject = subjectIn;
executor.addJob(new CronSchedule("0 0/5 * * * ?"),
"BulkEmailer",
new Runnable() {
public void run() {
emailer.execute(url + "/liftyourgame/", subject,
sendEmail);
}
});
}
In order to query the database the thread needs a hibernate session of
its own as hibernate sessions are per thread.
Currently it creates a session and DAO like so:
public synchronized void execute(String url, String subject,
SendEmail sendEmail) {
// For each mailout fetch url and send mailout
if (factory == null) {
Configuration cfg = new Configuration();
factory = cfg.configure().buildSessionFactory();
}
Session session = factory.openSession();
userDAO = new UserDAOImpl(session);
/////
This means I need to add all of my entities in hibernate.cfg.xml:
<mapping package="com.liftyourgame.application.entities"/>
<mapping class="com.liftyourgame.application.entities.Action"/>
<mapping class="com.liftyourgame.application.entities.DailyQuote"/>
<mapping class="com.liftyourgame.application.entities.Goal"/>
<mapping class="com.liftyourgame.application.entities.Image"/>
<mapping class="com.liftyourgame.application.entities.LygEntity"/>
<mapping class="com.liftyourgame.application.entities.Measure"/>
<mapping class="com.liftyourgame.application.entities.Measurement"/>
<mapping class="com.liftyourgame.application.entities.Role"/>
<mapping class="com.liftyourgame.application.entities.User"/>
Tapestry doesn't seem to need these mappings for my web application as
tapestry-hibernate seems to scan all classes in the entities package.
Is there some way I could use tapestry-hibernate to setup a session for
my thread?
Regards,
Greg