Sikander
Sikander

Reputation: 862

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

Upvotes: 2

Views: 300

Answers (1)

Sikander
Sikander

Reputation: 862

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();

Upvotes: 3

Related Questions