Groovy and JPA

Tutorial about how to use Hibernate from within Groovy making use of Groovy Templating:

import javax.persistence.*

class JpaTemplate {

    EntityManagerFactory emf

    EntityManager em

    JpaTemplate(pu) {
        if (!pu) pu = "default"
        emf = Persistence.createEntityManagerFactory(pu)
    }

    void doInEntityManager(c, shutdown) {
        em = emf.createEntityManager()
        em.getTransaction().begin()
        c(em)
        em.getTransaction().commit()
        em.close()
        if (shutdown) shutdown()
    }

    void shutdown() {
        emf.close()
    }
}

And here is how to use the template that was defined above:

new JpaTemplate().doInEntityManager({ em ->
    em.createQuery("delete Contact").executeUpdate()
    em.persist new Contact(name:'Dan Allen', email: 'dallen@example.com')
}, true)

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>