0
votes

In a grails service, I create and manage a session for callinng methods from an external API, using the session factory of the API to initiate the connection:

1) Service Session objects (service level):

private final SessionFactory sessionFactory = SessionFactoryImpl.newInstance()
private Session session

2) Service getSession method calls

def getSession(Map conf) {
        if (session == null) {
            ...

            Object o = sessionFactory.getRepositories(params)
            session = o.createSession()
        }
        session
}

3) A service connector which is called from controller

def connect() {

<some logic>
        return session
    } 

4) In controllers, I retrieve the session object with :

def session = service.connect()

Once the session object has been created by the first connection, what is the best way to share it between controllers (even outside from the grails plugin) ? How to be sure that the session object is called as a singleton (i.e avoiding each controllers' methods calls to re-initialize the sessionFactory call in the service) ?

1

1 Answers

5
votes

Grails already have a SessionFactory bean, you can just declare it and dependency injection will handle it for you.

Regarding the use of the same session between controllers, how you will handle concurrent requests from different users?

Some thoughts:

  • If your external API are have hibernate classes, you can map them with xml.

  • If your external API needs a SessionFactory, just declare it in your services

  • If you need the current session, just use withSession.

Example of dependency injection:

class MyService {
  def sessionFactory
  ...
}