Hibernate.groovy
import
org.hibernate.cfg.Configuration
import
org.hibernate.Session
import
org.hibernate.SessionFactory
import
org.hibernate.Transaction
import
org.hibernate.tool.hbm2ddl.SchemaUpdate
class
Hibernate {
def
static
sessionFactory
static
{
try
{
Configuration cfg
=
new
Configuration()
cfg.configure()
new
SchemaUpdate(cfg).execute(
true
,
true
)
sessionFactory
=
cfg.buildSessionFactory()
}
catch
(Exception e) {
e.printStackTrace()
}
}
Hibernate() {}
private
Session getSession() {
return
sessionFactory.openSession()
}
Object execute(closure) {
def s
=
getSession()
def tr
=
null
def result
=
null
try
{
tr
=
s.beginTransaction()
result
=
closure.call(s)
tr.commit()
}
catch
(Exception e) {
e.printStackTrace()
if
(tr
!=
null
) {
tr.rollback()
}
}
finally
{
s.close()
}
return
result
}
void
saveOrUpdate(obj) {
def saveClosure
=
{ s
->
s.saveOrUpdate(obj) }
execute(saveClosure)
}
List executeQuery(hql) {
execute({ s
->
s.createQuery(hql).list() })
}
List executeQuery(hql, parameters) {
def query
=
{ s
->
def q
=
s.createQuery(hql)
if
(parameters
!=
null
) {
for
(i in
0
..parameters.size()
-
1
) {
q.setParameter(i, parameters[i])
}
}
q.list()
}
execute(query)
}
def get(clazz, id) {
return
execute({ s
->
s.get(clazz, id) })
}
void
delete(obj) {
execute({ s
->
s.delete(obj) })
}
}
Instead of interface, I use Closure for callback
Blogged with Flock
Tags: hibernategroovy