Could someone explain the difference to me between these code samples (Grails 3.3.11)
Session session = sessionFactory.openSession()
Person person = new Person()
person.firstName = "John"
person.lastName = "Roy"
person.address = "New York"
session.save(person)
and
Person person = new Person()
person.firstName = "John"
person.lastName = "Roy"
person.address = "New York"
person.save(person)
One difference is that session.save(person)
will work with any entity that is mapped in that Hibernate session where person.save()
only works with GORM entities (which are also mapped in the Hibernate session for you).
When using GORM there really aren't good reasons to use session.save(person)
.
I know that you didn't ask about best practice or about GORM Data Service but related to your question...
With recent versions of GORM best practice would be to have an abstract GORM Data Service like this...
import grails.gorm.services.Service
@Service(Person)
interface PersonService {
Person save(Person p)
}
And then inject that wherever you want to do the save. For example, in a controller:
class SomeController {
PersonService personService
def someAction() {
Person p = new Person()
// ...
personService.save p
// ...
}
}