Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain belongsTo in Grails

From the Grails belongsTo documentation, what is the use of

   class Book {
    static belongsTo = Author
}

What is the impact of cascading operations on Book, when CRUD operations performed on Author?

EDIT:

Thanks for your responses, may be i didn't specify my question correctly. I would like to know the difference between

 static belongsTo [author:Author]

vs

 static belongsTo = Author
like image 367
CSR Avatar asked Feb 06 '14 03:02

CSR


People also ask

What is static mapping in Grails?

The mapping static property configures how GORM maps the domain class to the database.

What is Grails domain class?

A domain class fulfills the M in the Model View Controller (MVC) pattern and represents a persistent entity that is mapped onto an underlying database table. In Grails a domain is a class that lives in the grails-app/domain directory.

What is Grails Gorm?

GORM is the data access toolkit used by Grails and provides a rich set of APIs for accessing relational and non-relational data including implementations for Hibernate (SQL), MongoDB, Neo4j, Cassandra, an in-memory ConcurrentHashMap for testing and an automatic GraphQL schema generator.


1 Answers

belongsTo is helpful if you need a reference back to the owning object. In this case it is likely that an Author has many Books. But maybe you're using a book object and want to mention that book instance's Author. That is a good way to get it.

As far as CRUD goes, deleting or updating the book will not do anything to the Author, but deleting the Author will delete the Book. If you don't add belongsTo then there will be no cascading saves/updates/deletes, you will have to do it manually.

Example:

def a = new Author(name: 'J.K. Rawling')
a.addToBooks(new Book(title: 'Harry Potter 1'))
a.addToBooks(new Book(title: 'Harry Potter 2'))
a.save()   // Saves author and book instances

a.delete() // Author and both books are deleted

Edit:

The OP updated their question, and I'm honestly not sure what the answer would be. Hopefully Burt Beckwith will show up soon! Good question, OP.

like image 134
grantmcconnaughey Avatar answered Sep 27 '22 19:09

grantmcconnaughey