Saturday, November 4, 2017

Configuring Grails DDL | Table Configuration | Grails DDL Schema Configuration | Table Schema Structure

Configuring Grails DDL | Table Configuration | Grails DDL Schema Configuration | Table Schema Structure


You need to create your own configuration class as below:


package com.multidb.gorm

import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration
import org.hibernate.HibernateException
import org.hibernate.cfg.Configuration
import org.hibernate.dialect.Dialect
import org.hibernate.tool.hbm2ddl.DatabaseMetadata
import org.hibernate.tool.hbm2ddl.SchemaUpdateScript

class MyDbConfigClass extends GrailsAnnotationConfiguration {
    private GrailsApplication grailsApplication
    public static Configuration configuration = null

    @Override
    protected void secondPassCompile() {
        super.secondPassCompile()
        if (!configuration) {
            configuration = this
        }
    }

    @Override
    String[] generateDropSchemaScript(Dialect dialect) throws HibernateException {
        return checkAndRemoveIgnoredTables(super.generateDropSchemaScript(dialect));
    }

    @Override
    String[] generateSchemaCreationScript(Dialect dialect) throws HibernateException {
        return checkAndRemoveIgnoredTables(super.generateSchemaCreationScript(dialect));
    }

    @Override
    List<SchemaUpdateScript> generateSchemaUpdateScriptList(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException {
        return super.generateSchemaUpdateScriptList(dialect, databaseMetadata)
    }

    @Override
    String[] generateSchemaUpdateScript(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException {
        List<SchemaUpdateScript> scripts = super.generateSchemaUpdateScriptList(dialect, databaseMetadata)
        return SchemaUpdateScript.toStringArray(scripts)
    }

    private static String[] checkAndRemoveIgnoredTables(String[] sqlStatements) {
        println(sqlStatements)
        return sqlStatements
    }

    @Override
    void setGrailsApplication(GrailsApplication application) {
        // Run superclass method
        super.setGrailsApplication(application)

        // Inject Grails application reference
        this.grailsApplication = application
    }
}


Below is DataSource configuration:


dataSource {
    configClass = com.multidb.gorm.MyDbConfigClass
    driverClassName = "com.mysql.jdbc.Driver"
    dbCreate = "create"
    url = "jdbc:mysql://localhost/grails_db"
    username = "grails"
    password = "grails"
}

No comments:

Post a Comment