Search code examples
hibernategrailsgroovygrails-orm

Accessing database from Java classes in grails


I am working on a grails project. I am able to access database from controllers and services. Now I want to access and change the database from src/java classes. is this possible and if so what are the required configuration ?? Thanks


Solution

  • I got it. We have to get the Application context in our class like this

    ApplicationContext context = (ApplicationContext) ServletContextHolder.getServletContext()
                .getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
        SessionFactory sf = context.getBean('sessionFactory');
    
        Session session = sf.getCurrentSession();
        Sql sql = new Sql(session.connection());
        String query = "select * from message";
        sql.execute();