I'm still kind of new to Grails (and Groovy), so apologies if this question seems dumb.
I'm trying to access a SQL database, and it seems that I could use SQL commands in the Controller (taken from this StackOverflow question ):
import groovy.sql.Sql
class MyFancySqlController {
def dataSource // the Spring-Bean "dataSource" is auto-injected
def list = {
def db = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app
def result = db.rows("SELECT foo, bar FROM my_view") // Perform the query
[ result: result ] // return the results as model
}
}
I know that if I were to create a domain class with some variables, it would create a database table in SQL:
package projecttracker2
class ListProject {
String name
String description
Date dueDate
static constraints = {
}
}
but this would create the table named "list_projects". If I didn't do that and just created the SQL table outside of Grails, and if this follow-up question says that you can disconnect the Domain class from your database, what purpose do Domain classes serve? I'm looking to do some sql queries to insert, update, delete, etc. data, so I'm wondering what's the best way to do this.
Domain classes are used to model your domain of knowledge within your application. This is not only the structure of the data but also the basis of interaction of those models within your domain of knowledge.
That said, there is no reason why you can't create a Grails project without any domain classes and use your own SQL statements to create, read, update, and delete data in your database. I have worked on projects where there was no domain classes and everything was modeled using DTO (data transfer objects) and services for accessing an already existing database and tables.
Of course by not using Domain classes you lose the integration with GORM, but that doesn't seem like an issue for your case (nor was it in the case I outlined above).
That's part of the beauty of Grails. You don't have to use all of it, you can use only the parts that make sense for your project.
In one of my projects I needed to dump the contents of a MySQL into a Lucene index. Creating the the whole domain class structure for such an one-off operation would be an overkill, so the groovy SQL API did just fine.
So, my answer is no, you DON'T have to use the domain classes if you don't want to.
I agree with what @joshua-moore have said, plus domain classes can drastically simplify you project if you use them properly
I agree to both answers but for your particular case, I would suggest having a domain model for the underlying table.
Reasons:
transactions
manually for update operation, if transaction is a requirement. With GORM and Hibernate, you get that handled automatically. db-reverse-engineer
plugin
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.