Last updated by admin 4 years ago
CRUD?? CRUD Operations
{excerpt:hidden=true} Grails domain classes use dynamic persistent methods to facilitate CRUD (Create/Read/Update/Delete) operations on persistent classes: {excerpt} Grails???????????????????????CRUD(??/??/??/??) ????????:?? Create
{excerpt:hidden=true} To create entries in the database, domain class instances support a "save" method which cascades to the instance relationships. In the example below we only call "save" on the author and both the Author and Book instances are persisted: {excerpt} ????????????????????????????"save"???????????????????????????????????????? ???????autur?"save"??????????????????????Author?Book?????????def a = new Author(name:"Stephen King") def b = new Book(title:"The Shining",author:a) a.books.add(b)// persist a.save()
def a = new Author(name:"Stephen King") .addBook( new Book(title:"The Shining") ) .addBook( new Book(title:"The Stand") )
?? Read
{excerpt:hidden=true} Grails supports a number of ways of retrieving domain class instances, for more detail on querying see the section on #Domain Class Querying, however to retrieve an instance if the "id" is known you can use the "get" static method: {excerpt}Grails????????????????????????????????????#Domain Class Querying??????"id"???????????"get"????????????????????????????????????????? Book.get(1)
Book.findAll() // retrieve all
Book.list(10) // lists first 10 instances
Book.listOrderByTitle() // lists all the instances ordered by the "title" property?? Update
{excerpt:hidden=true} The symantics of updating differ from that of saving a domain class. It is possible to update without explicitly calling "save" with the changes automatically being persisted if no exceptions occur: {excerpt}???????????????????????????????"save"?????????????????????????????def b = Book.get(1)
b.releaseDate = new Date()def b = Book.get(1) b.title = null // can't have a null title b.save() // won't save as fails to validate
def b = Book.get(1) b.publisher = "Print It"if(!b.validate()) { b.publisher = Publisher.DEFAULT }
b.validate(true)def b = Book.get(1)
b.title = "A New Title"// something happenedd to change your mind
b.discard()?? Delete
{excerpt:hidden=true} Domain class instances can be removed from the database by using the "delete" instance method: {excerpt}???????????????"delete" ???????????????????????????????????????def b = Book.get(1) b.delete()



