I'm having trouble accessing the EntityManager from within a grails service:
My setup is as follows...
- Basic Grails application with the AppEngine and GORM-JPA plugins
- Default settings for pretty much everything. I haven't touched resources.groovy, persistence.xml etc.
Some things are good...
- I am able to access the EntityManager from within controllers by simply adding "def entityManager".
But...
- I have a service that I'm trying to access the EntityManager from, however, I get a "java.lang.IllegalStateException: EntityManager is already closed!" exception.
Is a plugin closing the EntityManager somewhere? Do I need to change the scope of the EntityManager somehow? Is there some XML file I need to update to ensure proper injection?
class GoogleCalendarService implements InitializingBean { void afterPropertiesSet() { }
}def entityManager public OAuthToken getAccessToken(User u) { //can't access entityManager from here entityManager.newQuery(...) //throws an IllegalStateException }
One weird note: For some reason, if I re-save the service while Jetty is up and running the service is able to access the EntityManager just once. I开发者_JAVA技巧f I click reload (and have the controller access the service again) the service can no longer access the EntityManager...
I guess the right way to do this is use the EntityManagerFactory, like this:
import org.springframework.orm.jpa.EntityManagerFactoryUtils
class GoogleCalendarService implements InitializingBean {
void afterPropertiesSet() {
}
def entityManagerFactory
EntityManager em
public OAuthToken getAccessToken(User u) {
em = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory)
//do stuff with em
}
}
精彩评论