How to set proper relation among two classes - grails

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.

Related

House belongsTo Owner?

Wondering if "belongsTo" is write way to represent an ownership relationship where there is always a parent object, but the parent may switch.
ie if owner domain is
class Owner {
String name
}
Should House be:
class House {
String address
Owner owner
}
or
class House {
String address
static belongsTo = [owner: Owner]
}
What I want to achieve is bi-direction 1:1 where I can either access owner.house or house.owner and ability to change the owner without without deleting the old owner.
without deleting the old owner. ?
So you have two choices - by far the easiest and where your current method is actually wrong should be Should House be: maybe this?
class House {
String address
static hasMany = [owner:Owner]
Owner currentOwner
}
With the relationships as it is, you are saying a house has many owner's. So owner1 owner2 .. and it also has a current Owner which is Owner itself.
Each time you add a new entry you add it to the owner collection so house.addToOwner(owner) and you then set the last/latest update of currentOwner=owner.
If you want to navigate throw both entities, and the relation is 1:1 you can use hasOne
class Owner {
String name
static hasOne = [house: House]
}
class House {
String address
static belongsTo = [owner: Owner]
}

How to use mappedBy correctly in one to many relation

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

Creating one-to-many & many-to-many for same domain class in grails

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.

Unidirectional Many To One mapping with cascade

Is it possible to map the following with GORM?
I want to get rid off all associated events when I delete a person.
Person object should not have a link to events.( I want to avoid using hasMany on Person domain)
class Person {
String username
}
class Event {
String description
static belongsTo = [person:Person]
}
I'm getting now a 'Referential integrity constraint violation' when doing person.delete() because events are not removed before deleting person.
I don't think that is possible without using hasMany (speaking of which, why do you want to avoid that anyway?)
This SO Question states:
Hibernate only cascades along the defined associations. If A knows
nothing about Bs, nothing you do with A will affect Bs.
Use static hasMany and bam, problem fixed.
Edit:
The only way I think you could achieve this is using beforeDelete on the Person class to delete all the associated Events, i.e.
class Person {
def beforeDelete() {
def events = Event.findAllByPerson(this)
for (e in events) {
e.delete()
}
}
}
See the documentation on Events and Auto Timestamping for more info on that.
The above will not work
Why not define a no reference mapping:
class Person {
String username
static hasMany=[Events]
}
This way there is no actual bindings of events to person but a person can have many events

Grails domain class relationship to itself

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

Resources