...
...
Step-by-step guide for Example
GORM Shell Scripting needs transaction context
http://daviddawson.me/blog/2017/09/06/groovy-gorm-shell-script.html
Set a transaction context for a data source in GORM
Gorm has come along well and is pretty isolated from the surrounding Grails infrastructure now. All you need to do is to create a HibernateDatastore
(or other) and pass in a config and your domain classes for initialisation. Then, you can start to use them as you do in Grails.
One rub is that there is no natural place to wrap a transactional Session around. This appears as a hiernate exception related to no session being present. This is something often not noticed in a grails app, as its all created automatically by Grails, and is also created by a full fat standalone Gorm app when you’re using services with any form of transactional annotation. Yet, you need a session to use hibernate, which the RDBMS version of Gorm uses.
The solution is to use the .withTransaction
method added onto all grails domain classes. This creates a session and puts it into the thread context.
I did a light bit of syntax sugaring to hide that stuff and make things more readable, and its good to go!
Code Block | ||||
---|---|---|---|---|
| ||||
#!/usr/bin/env groovy
@Grapes([
@Grab("org.grails:grails-datastore-gorm-hibernate5:6.1.4.RELEASE"),
@Grab("com.h2database:h2:1.4.192"),
@Grab("org.apache.tomcat:tomcat-jdbc:8.5.0"),
@Grab("org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.5.0"),
@Grab("org.slf4j:slf4j-api:1.7.10")
])
import grails.gorm.annotation.Entity
import org.grails.datastore.gorm.GormEntity
import org.grails.orm.hibernate.HibernateDatastore
// Create the domain classes you want
@Entity
class Person implements GormEntity<Person> {
String firstName
String lastName
static mapping = {
firstName blank: false
lastName blank: false
}
}
//Guts of the script, do your db stuff here with the power of Gorm
gormScript {
new Person(firstName: 'Dave', lastName: 'Ronald').save()
new Person(firstName: 'Jeff', lastName: 'Happy').save()
new Person(firstName: 'Sergio', lastName: 'del Amo').save()
new Person(firstName: 'Monica', lastName: 'Crazy').save()
println "People = ${Person.count()}"
def sergio = Person.findByFirstName("Sergio")
println "Got ${sergio.firstName} ${sergio.lastName}"
}
def gormScript(Closure exec) {
Map configuration = [
'hibernate.hbm2ddl.auto':'create-drop',
'dataSource.url':'jdbc:h2:mem:myDB'
]
HibernateDatastore datastore = new HibernateDatastore( configuration, Person)
Person.withTransaction {
exec()
}
}
|
Info |
---|
sample code block
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
...