简体   繁体   中英

Grails - external database controllers and domains

I am new to Grails. I use my external mysql database. Do I have to make Grails domain classes for tables in my database (copy my database into domain model), or can I make controllers and views just for my external mysql tables without making domain classes?

Thank you for answers.

No you effectively mock the database tables in your domains.

In fact, if you build your domains first, they will automatically build your tables for you; many people find this the easier way as if you have a pre-existing database, you have to match the constraints PERFECTLY to get it to work.

There is no requirement that you must use GORM with Grails. You can in fact just use the classes and such from the groovy.sql package and interact with your database directly using SQL and 'GroovyRowResult' instead of domain classes.

However, if you don't use GORM you also lose a lot of scaffolding (eg to create the controllers and views) because you have no domain modeled.

Its better to declare your domain in class which could be related to database.

user domain class

class User {

    Long id
    String name

    static mapping = {
        table 'user'  //here user is database table name

        version false
        id column: 'id', generator: 'increment'
        name column: 'name'
    }

    static constraints = {
        id(nullable: true)
        name(nullable: false)
    }
}

you can use scaffolding in controller to generate CRUD as well like

class UserController {

    static scaffold = User
    def index() {
        def userList = User.list()
        [userList: userList]
    }
}

Without declaring your domain class you will get error to execute query from database in controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM