This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Grails/GORM: The meaning of belongsTo in 1:N relationships
I have 2 domain class with belongsTo association
class Teacher {
String name
String department
}
class Address {
String line1
String line2
// Teacher teacher //this line is commented.
static belongsTo = [teacher: Teacher]
static constraints = {
}
}
What is the advantage i get when i make Address belongsTo Teacher
do i need to declare teacher object reference in Address class (see the commented line in Teacher class)
The goal to have the belongsTo clause is to have bi-directional access from one class to the other. See Documentation of belongsTo.
You can omit the second declaring of teacher (you commented out).
So it should look like this:
class Teacher {
String name
String department
Set<Address> adresses = new HashSet<Address>() // here you could set a specific list/set data holder
static hasMany = [adresses:Address]
}
class Address {
String line1
String line2
static belongsTo = [teacher: Teacher]
static constraints = {
}
}
Here you have a one-to-many associaton, where both classes have access to each other. If you remove the belongsTo clause you can not access the teacher object from the adress object. This is also reflected in the database.
Goal of belongsTo isn't making the relations bidirectional - The goal is to specify which side of the association takes the ownership and to define the behavior of cascading save and delete operations
Read this documentation it explains every thing you need to know about belongsTo.
Related
I am having some issues with setting relation among two classes. I have 2 classes, Student:
class Student {
String name
Guardian father
Guardian mother
Guardian local_guardian
}
and Guardian:
class Guardian {
String name;
static hasMany = [children:Student]
static mappedBy = [children:'father']
}
Here, I used mappedBy to map Guardian object to father property . Unless mappedBy, I was getting error telling, should use mappedBy with any of the 3 Student class property.
I tried this query to enter some sample data
new Student(name:"John", father: new Guardian(name:"Michael").save(),
mother: new Guardian(name:"Mary").save(),
local_guardian: new Guardian(name:"James").save()).save(flush:true);
The data is getting saved successfully but my problem is, Since I used mappedBy with 'father' property, I am able to use Guardian.children only with that father object.
when I try to get list of children with mother and local_guardian object,
(eg: mother.children) getting null result.
I tried by adding with addTo on the many side like
Guardian.findByName("Mary").addToChildren(
Student.findByName("John")).save(flush:true);
and tried accessing
Guardian.findByName("Mary").children
Here, I got the result , but it moved the child from father to mother object, and no longer able to access father.children
How will I solve this scenario?
What I am trying to achieve is, I should be able to get list of children from all 3 of the Guardian object . Here One Student object is pointing to 3 Guardian objects (father, mother, local_guardian) . So I should be able to get the list of children by
father.children
mother.children
local_guard.children
How will I set the proper relation among these classes to solve my problem?
If you want to implement this relation using hasMany then you will need to have three mappedBy in Guardian class.
static hasMany = [children:Student, motherChildres:Student, localGuardianChildrens:Student]
static mappedBy = [children:'father', motherChildrens:'mother', localGuardianChildrens: 'local_guardian']
But this does not look good, instead you can implement a relation using a middle level domain class and add addToChildren and getChildrens methods in Guardian class like below.
class GuardianChildren {
Guardian guardian
Student student
constraints {
student unique: ['guardian']
}
}
Guardian {
void addToChildrens(Student child) {
new GuardianChildren(guardian:this, student:child).save()
}
#Transient
List<Student> getChildrens() {
return GuardianChildren.findAllByGuardian(this).children
}
}
Student {
#Transient
Guardian getMother() {
//find guardin children where guardian type is mother and children is this student
}
#Transient
Guardian getFather() {..}
}
Remove hasMany from Guardian and father/mother properties from Student. You will also probably need a type field in Guardian to specify if this is mother/father etc
You likely want to use hasMany and belongsTo, then to define the guardian you might want to use something like a father, mother, localGuardian properties in the guardian object. With such a relationship you can then use transients to define the set of children and mother / father.
So for example
class Student
{
String name
Guardian local_guardian
static belongsTo = [primaryGuardian: Guardian]
static transients=['mother', 'father']
//define the transients
def getMother(){
if(primaryGuardian.type == 'mother') {
return primaryGuardian
} else {
return primaryGuardian.spouse
}
}
//do something similiar for getFather
}
Class Guardian
{
String name
String type
Guardian spouse
static hasMany = [children:Student, localGuardianStudents: Student]
}
Please note that this is just example code and may contain errors as I didn't test it.
So you can then create a guardian, and then add children by calling
guardian.addToChildren(child)
Anyways, this will let you get the children of a guardian by calling guardian.children, it lets you get the primary guardian (either the mother or father) of the child by calling child.primaryGuardian, and it lets you get the mother or father by calling child.mother without the need to add special types in there.
You will want to make sure that you modify the constraints here, so that the spouse could be null. Furthermore relationships of this nature can sometimes get tricky when creating them causing errors relating to missing ID numbers when you are trying to save, so you want to be sure that you make sure that both sides of the relationship are defined when you create and modify these objects.
I am new to grails. I have a problem with one to many relation with my two classes. I have two classes Person and Child as follows
class Child
{
String name
String grade
Person father
Person mother
Person guide
}
and Person class looks like
class Person
{
String name
hasMany[child: Child]
}
How do I use mappedBy here correctly
I have looked here . The example given in that link shows mappedBy when the many side has two properties of parent class. how do I use here mappedBy correctly? What difference does it make in the database level? Please help..
You can do it like this
class Person {
static hasMany = [childs: Child]
static mappedBy = [childs:'father'] //or whichever parent you want to use
}
As you have only one collection in Person domain, you can map it to just one parent. If you want to map childs for all three parents, you will need three collections in the Person
I want to create a domain class as like , One user can post many orders [Bidirectional] and one order can be liked by many users [unidirectional].
I have written a domain class as shown below ,
Class User {
String userName;
List orders
static hasMany = [Order]
}
Class Order {
String orderId
String orderName
//Indicates this order belongs to only one user
static belongsTo =[owner : User ] // Bidirectional
//Indicates order can be liked by many users
static hasMany = [likedUser : User] //Unidirectional
}
But I am getting am error saying invalid schema . Any body please help...
This post looks similar to my question but I am not getting , Please help.
First, order is a reserved word in SQL. Since GORM by default creates a table with the same name as your class, you'll need to either rename your class or provide a different name to use when mapping to SQL tables.
For example:
class Order {
static mapping = {
table 'user_order'
}
// ...
}
Another problem is that Order contains two associations to User. You need to tell GORM which one of these that is the bi-directional association from User to Order. That can be achieved using mappedBy, like this:
class User {
String userName
static hasMany = [orders: Order]
static mappedBy = [orders: 'owner']
}
Hope this helps.
I have some domain class Incident,Problem, Category, Impact, Urgency etc.
Class Incident
{
Category category
String subject
Impact impact
}
Class Problem
{
Urgency urgency
Category category
String title
}
Class Category
{
String categoryName
String description
}
now, some rows are inserted into this class. now if I am deleting category it throws error like 'grails cannot delete or update a parent row'..
so what I have to do for deleting?
The problem is - you have reference to Category in Incident and Problem classes, so database tables for those classes will have Foreign key on category table, so you can not delete a category untill you either remove those incidents/problems or update those incidents problems and set category to null (you will have to make them as nullable in domain constraints)
So either you do
Problem.executeUpdate('update Problem p set category = null where category = ?', [category])
Same for incidents
Or you can model your domain classes using belongsTo and hasMany and grails will handle every thing automatically
Some thing like
class Problem {
static belongsTo = [category:Category]
}
class Category {
static hasMany = [
problems: Problem
]
static mappings = {
problems cascade: "all-delete-orphan"
}
}
I would prefer to manage relationships using belongsTo, hasMany, hasOne rather then just using references, it expresses the model better.
It depends on your domain model as well, in your business can problems, incidents exist without a category ! or they must belong to some category. If your answer is first option, your dont want to cascade delete, but update those incidents/problems with null category, if your answer is second option - you needs cascade all-delete-orphan
How your Category looks like, is it belongsTo Incident domain class,if category belongs to some domain class you can not delete it.
Ref : See here
I need a way to be able to have a domain class to have many of itself. In other words, there is a parent and child relationship. The table I'm working on has data and then a column called "parent_id". If any item has the parent_id set, it is a child of that element.
Is there any way in Grails to tell hasMany which field to look at for a reference?
This is an example of what you are looking for (it's a snippet code I am running and it generates column parent_id). I don't think you need SortedSet:
class NavMenu implements Comparable {
String category
int rank = 0
String title
Boolean active = false
//NavMenu parent
SortedSet subItems
static hasMany = [subItems: NavMenu]
static belongsTo = [parent: NavMenu]
}
Furthermore, you can give name to the hasMany clause using the Mapping DSL, which is explained at http://grails.org/GORM+-+Mapping+DSL