Monday, May 31, 2010

Relationship Advice : Grails One-To-Many

If you are here investigating bigamy.... you have come to the wrong place.... We are actually going to have a quick once over on One-To-Many relationships in Grails and GORM (Let's abbreviate to OTM for the sake of my fingers). Here's what we'll cover:

  • Starting a Relationship
  • Living and Working With Your Relationship
  • Finding out more about your Relationship (or querying :) )
  • What if you don't belongTo someone?

Starting a Relationship :

First of all, what is an OTM? Let's let the code do the talking:

class Parent{
static hasMany = [children:Child]
String name
}

class Child {
static belongsTo = [parent:Parent]
String name
}


Here is a very simple domain model that will serve as a nice concise example. We have a Parent domain that can 'haveMany' children... in turn these children belongTo a specific parent. This is quite a 'tightly coupled' OTM. There can be a few nuances that catch people out here, which of course we will cover... (we will take a brief look at the "loosely coupled" OTM too).

The definition of the hasMany in the Parent class is actually a Map, and it should read like [collectionName:TypeContainedInCollection], so the parent has a collection with the name 'children', that will contain instances of the Child domain class.

Similarly in the Child class, the 'belongsTo' property is also a Map, [instanceOfOwningClass:typeOfOwningClass]. The 'belongsTo' property forms what I referred to earlier as a 'tightly coupled' OTM. This basically entails that the children instances are 'owned' by their 'parent', this in turn has some interesting side effects that we will cover now.

Living and Working With Your Relationship :

OK let's create a parent with some children :

def parent = new Parent(name:'Dad')

//add a new child instance
parent.addToChildren(new Child(name:'son'))

//add another child instance using a map
parent.addToChildren([name:'daughter'])

//save the parent
parent.save(flush:true,failOnError:true)

To add a Child to a Parent we use the 'addTo' method that is provided by Grails, it is basically addTo+Name of Association. When we use these methods, GORM will wire up our domain classes and because children have a 'belongsTo' property set, calling save() on the parent will also validate and save the children... sweetness :)

OK now... what if we need to remove some children from our relationship.... easy....

//retrieve our parent
def parent = Parent.findByName('Dad')

//retrieve the child instance
def child = Child.findByName('son')

//remove the child
parent.removeFromChildren(child)

parent.save()

Oh.... wait.... NOT EASY!!! If we run the above code we get the following Exception:

"not-null property references a null or transient value: Child.parent"

Yeeeeeeeeesh.... not pretty... The knee jerk reaction here might to add a nullable constraint for the parent property in the Child class... but this would be wrong. The relationship we defined has a 'belongsTo' so in this case, if we remove a child.... we simply want it to be deleted automatically at the same time. To achieve this, our Parent domain must look like:


class Parent{
static hasMany = [children:Child]
String name

static mapping = {
children cascade: "all-delete-orphan"
}
}

Now if we re-run the previous code, the child instance will be removed from our relationship and also deleted!


Finding out more about your Relationship :

If we have a Parent instance, it is rather easy to query for our children.... we simply access them as a property:

def parent = Parent.findByName(name:'Dad', [lazy:[children:false]])
parent.children.each{//do something}

However, things are not so clear cut when coming from the other direction. Suppose we have the name of a child and we want to find all the parents that have children with that name, so basically querying the relationship from the many side:

def name = 'son'

//create criteria so we can perform a criteria query
def c = Parent.createCriteria()

//perform a listDistinct as querying relationships can result in duplications
def parents = c.listDistinct{
createAlias("children", "c")
eq("c.name", name)
}

Thanks to Robert Fletcher for blogging on this (link to follow)....

What if you don't belongTo someone? :

In brief, if you define an OTM without declaring a 'belongsTo' property as we have, you're Child instances can exist on their own, without the need of being attached to a parent. One side effect of this is that the cascading save behaviour we saw before does not apply here... you will need to call save() on each domain separately.

So there we have it.... defining, creating and querying a One-To-Many relationship in Grails... I hope this has been helpful to anyone that comes across it! Happy trails!

Resources :
http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html
http://www.grails.org/GORM+-+Defining+relationships

Constraining across relationships:
http://johnrellis.blogspot.com/2009/09/grails-constraints-across-relationships.html

37 comments:

  1. what if you have two parents or a grandParent? how do you define belongsto for multiple owners?

    ReplyDelete
  2. Sorry for the delay, I am unsure how to define a belongsTo for multiple parent, might be one for the user list. I know you can do, belongsTo = [MyFirstClass,MySecondClass] but I am not sure how to define it so you can have an instance as in belongsTo = [myInstance:MyClass]...

    Try the user list :)

    ReplyDelete
  3. Excellent article i am sure that i will come back here soon!

    ReplyDelete
  4. How can I capture all the validation errors occurring in the child when I call parent.save() so that I can display all the errors at once on the screen.
    e.g nameMapList.each{nameMap ->
    parent.addToChild([name:'daughter'])
    }
    parent.save(flush:true,failOnError:true)

    so now, if we loop 10 times, I need to have all the 10 errors so that I can display them on the screen at once?

    ReplyDelete
  5. Hey,

    I always thought that retrieving errors on the parent would display all those in the children that were preventing the save.

    Can you confirm in test code that this is not the case??

    John

    ReplyDelete
  6. I want to show list of all children(with all of their propertis)-short children 'list' view related to parent.How i can do this?

    ReplyDelete
  7. Thanks a lot, the steps are easy to understand and implement.

    ReplyDelete
  8. I'm gladsome to mature so more serviceable and informative assemblage on your website.
    Good Relationship With Golden Sparrow Mag

    ReplyDelete
  9. Best way to save your marriage? visit our websites just click the links.
    and find more tips about relationship.
    Visit one great deals
    Visit relationship advice

    ReplyDelete
  10. Best way to save your marriage? visit our websites just click the links.
    and find more tips about relationship.
    Visit one great deals
    Visit relationship advice

    ReplyDelete
  11. Has anything ever bothered you in life? Do you
    have any problem you need to solve? A pending
    court case you want to resolve in your favor?
    Health, relationship and finance. Welcome to
    the world of miracles and wonders, there are
    supernatural treasure and power to liberate
    mankind from all afflictions. Why cant you live a
    life of your dream? Why must you work so hard
    and yet earn so little? Why cant you be happy
    with the one you love and desire or why cant the
    one you love reciprocate and appreciate that
    love? Why would the doctor tell you there is no
    solution or cure to your problems? Why would
    your lawyer say you stand no chance, that your
    case is hopeless? Have you been cheated by
    anyone or those owing you money refuse to pay
    back? Do you need a rapid job promotion in
    your place of work? You want to venture into
    politics? Now I understand certain things are
    hard to believe and comprehend, but all I ask
    from you is only 3 days and if you will follow my
    instructions and use the items you will receive, I
    promise your life will never be the same
    again.If you find no relevance in the help I offer
    I solemnly appeals do not be vindictive and go
    in peace. And if your intentions are to take
    advantage of the powerful nature of our items
    for the purpose of evil, I will not have any
    business with you please be advised. May
    angels guide you. All inquiries should be
    directed to the Priest Abija email below Email:
    spirituallighthealing101@live.com or
    you can sent a text message to this number:(518) 303-6207!

    ReplyDelete
  12. I never ever read such type of info before this was really incredible. Discover The Cove Wine

    ReplyDelete
  13. I absolutely feel delighted once I realize articles appropriate to my work and my subject. National Retail Theft Database Articles

    ReplyDelete
  14. I am dreadfully thankful to all of your team for sharing such motivating information. Click Scuba EXPO Link

    ReplyDelete
  15. I want to give a special thanks to the prophet that helped me got
    my partner back. my name is long Steven, early this year, i
    and my wife started having some issues and she left me and the
    kids even when i loved her so much. I was frustrated to the extent
    that i started looking for links on the internet on how to get her
    back. One day i came across a testimony in which a lady was
    testifying of how this prophet helped her got her man back i was
    able to contact this prophet and helped me put everything in
    order and my wife came back to me just as i wanted. this prophet
    is great if you know you have any problem here is his email
    address prophet.drmuksolutiontemple@hotmail.com

    ReplyDelete
  16. After six years in marriage with my husband with 3 kids, he suddenly started going out with other women and coming home late, each time i confronted him it turns out to be a fight and he always threatened to divorce me at all time, my marriage was gradually coming to an end. i tried all i could to stop him from this unruly attitude but all proved abortive, until i saw a post in the forum about a spell caster who helps people cast spell on marriage and relationship problems, at first i doubted it but decided to give it a try, when i contacted this Spell caster Dr. Dangogo via email, he helped me cast a spell and within 4 hours my husband came back apologizing for all he has done and promised never to do such again and today we are happily together again. Contact this Great spell caster for your marriage or relationship issues via this email; dr.dangogospell@gmail.com

    ReplyDelete
  17. Are you worried about your marriage ? Get few sessions of our Intuitive Coaching and you can get improvement in your relation within 30 days or less. Contact for sessions!

    How do I get over my ex

    ReplyDelete
  18. Seriously awesome blog!Really great content
    Your blog is a lesson for those couples who are in critical stage of their relation!
    I know one couple who lives in my neighbour and i am seeing them fighting from the last 8 years i feel really bad for them and i wanted to help them as well !
    Therefore i am looking for such positive content loveinaclick.org/
    I will suggest your blog as well.I really wish and hope that they stop fighting !

    ReplyDelete
  19. This blog has helped bring me closer to my children

    ReplyDelete
  20. I am so glad that Grails has brought such happiness to obviously troubled souls. Isn't code wonderful!

    ReplyDelete
  21. I am so glad that Grails has brought such happiness to obviously troubled souls. Isn't code wonderful!

    ReplyDelete
  22. I want to thank God for using Dr Okougbo Alaba as my source of savior after 2 year of joblessness and my lover left me alone for 2 years,Have just been heart broken until i go in contact with Dr Okougbo Alaba after i saw a lady testimony on how she was helped by this same dr Okougbo Alaba, So i decided to get in contact with him and when i told him all my problem he laughed and said this is not a problem that everything will be ok in 3days time. Exactly the 3rd day my ex lover called me i was shocked and what surprise me the most was that a company i applied for over 4month called me and said i should resume work as soon as possible.Am so grateful to Dr Okougbo Alaba if you wish in contacting him realhomeofspell@outlook.com He do cast the spell as following
    (1) If you want your ex back.
    (2) you need a divorce in your relationship
    (3) You want to be promoted in your office.
    (4) You want women & men to run after you.
    (5) If you want a child.
    (6) You want to be rich.
    (7) You want to tie your husband & wife to be yours forever.
    (8) If you need financial assistance.
    (9) Herbal care
    Contact him today on: realhomeofspell@outlook.com

    ReplyDelete
  23. Am Tanya Albert,my fiance and I kept on getting into fights all of the time. We were close to breaking up a few times. I knew that we needed something to stay together because he was pulling away from me day by day. Dr Ekpiku really helped us stay together and become a closer couple. He did a love binding spell that worked perfectly! He started making more of an effort to talk to me about how he was feeling which helped us work through our problems so much better. My fiance tends to shut down whenever there is conflict and this spell helped him communicate with me. I can also tell that he is more attracted to me because he keeps sending me flowers at work and is always trying to touch me in some way. It's actually really nice and I am very grateful to Dr Ekpiku and his temple at Ekpikuspelltemple@live.com for all that he have done for me.

    ReplyDelete
  24. My name is Sharon Doroes, I have to give this miraculous testimony, which is so unbelievable until now. I had a problem with my Ex husband 2 years ago, which lead to our break up. I was not myself again, i felt so empty inside me, my love and financial situation became worst, until a close friend of mine told me about a spell caster who helped her in the same problem, his site http://magical-rituals.com . I sent email the spell caster and i told him my problem and i did what he asked of me, to cut the long story short. Before i knew what was happen, less than two weeks my husband gave me a call and told me that he was coming back to me i was so happy to have him back to me. The most interesting part of the story is that am pregnant. Thanks to Doctor Samael for saving my marriage.

    ReplyDelete
  25. What do i stand for in this world without my lover by my side?, This was the taught that was running through my mind when my lover departed from me. You know one thing i believe in is that once you are having problems that are bringing you down God always use people to raise you up. In my case it was Dr.Zadson that was used in helping me get my lover back, Since the help of Dr.Zadson i must say that my relationship has been filled with more love and as a matter of fact my lover never does a thing without me. So you see this is the more reason why i must thank Dr.Zadson and the more reason why i must put his details on this site to enable other people contact him via email
    eduduzadsontemple@yahoo.com

    ReplyDelete
  26. How to get your ex husband back
    My name is Jessica Ruiz from Florida I have to give this miraculous testimony, which is so unbelievable until now. I had a problem with my Ex husband 2years ago, which lead to our break up. when he broke up with me, I was not my self again, i felt so empty inside me, my love and financial situation became worst, until a close friend of mine Lucy told me about a spell caster who helped her in the same problem too his name is Dr Shiva at hinduspelltemple@yahoo.com . I email Dr Shiva the spell caster and i told him my problem and i did what he asked of me, to cut the long story short. Before i knew what was happening my husband gave me a call and told me that he was coming back to me in just 2days and was so happy to have him back to me. We have two kids together and we are happy with ourselves. Thanks to Dr Shiva hinduspelltemple@yahoo.com for saving my relationship and for also saving others own too. continue your good work, If you are interested to contact him and testify this blessings like me, the great spell caster email address is hinduspelltemple@yahoo.com you are the best among all the spell caster online I hope you see my testimonies and also pray for my family too.
    Once again thank you Dr Shiva at hinduspelltemple@yahoo.com

    ReplyDelete
  27. My name is Elizabeth morgan , From USA ,and I’m happily married with a lovely husband and three children.I had a very big problem with my husband few months ago,to the extent that he even packed his things away from our house. He left I and and my kids for almost 1year, and i tried all my possible best and effort to bring him back.I discussed it with a very good friend of mine,and he gave me an advice concerning a spell caster, that he is the only one that can handle my situations and problem,that he’s always ready and able to do anything related to spell casting and helping of the needy, Please every every one i would like you all to contact him with his email address,which is as follows.”orikiolodumarespelltemple@outlook. om". I never believed in spell casting,but My friend convinced me and i had no choice than to follow my friend advice,because i never dreamed of loosing my lovely Husband. And i contacted him with his email address,and i discussed with him all my problems and worries and so surprisingly,he told me that I’ll get my husband back a day after. I didn't believed Him, until when i got home,the next day,my husband called me to inform me that he is coming back home…..So Amazing!! That’s how i got my back through spell casting and our relationship was stronger than ever. One of the price i was asked to pay was to tell it to the people around me that problems like this,can always be solved by Dr. Olodumare. So! my advice to you out there is to visit this same E-mail address,and tell him your problems too,if you are in any condition related to love issue or getting your ex back or and problem at all, please Contact him and have a happy life. you can contact him via email (orikiolodumarespelltemple@outlook.com )
    CONTACT HIM TODAY VIA THIS EMAIL ADDRESS: orikiolodumarespelltemple@outlook.com AS HIS POWERS ARE SO STRONG AND VERY EFFECTIVE AND HAS NO BAD EFFECT INSTEAD IT HAVE A VERY GOOD RESULT AFTER CASTING THE SPELL.

    ReplyDelete
  28. Love Spell To me this is the only way that ensures you and that someone you love will always be together just as they promised you. My marriage had its own trouble bigger than counseling, Understanding and all the things a relationship is built upon the only thing that worked for me was the spell OTIS DARKO did for me. It was the only help that i seeked that actually worked for me that is why i am saying it the Ultimate. My friend who advised me to contact a spell caster has stayed married to her husband for ten year and some months now because of the love spell OTIS DARKO did for her.I cannot talk about mine because its just been two months now.I you want to save your your relationship contact the spell caster with this email otisdarko60@yahoo.com

    ReplyDelete
  29. Midred Jackson Says

    Am giving this testimony cos am happy

    My name is Midred Jackson from Michigan I never believed in love spells or magic until i met this spell caster once. when i went to Africa in June 28th 2013 this year on a business summit. i ment a man called DR OTIS DARKO. He is powerful he could help you cast a spells to bring back my love’s gone,misbehaving lover looking for some one to love you, bring back lost money and magic money spell or spell for a good job.i’m now happy & a living testimony cos the man i had wanted to marry left me 3 weeks before our wedding and my life was upside down cos our relationship has been on for 2 years… i really loved him, but his mother was against me and he had no good paying job. so when i met this spell caster, i told him what happened and explained the situation of things to him..at first i was undecided,skeptical and doubtful, but i just gave it a try. and in 6 days when i returned to taxes, my boyfriend (is now my husband ) he called me by himself and came to me apologizing that everything had been settled with his mom and family and he got a new job interview so we should get married..i didn’t believe it cos the spell caster only asked for my name and my boyfriends name and all i wanted him to do… well we are happily married now and we are expecting our little kid,and my husband also got a new job and our lives became much better. in case anyone needs the spell caster for some help, email address: otisdarko60@yahoo.com

    GREAT OTIS DARKO I thank you very much thank you in 1000000 times.. if not you I would have been losted and wasted thank you. Email Him Through his email address... otisdarko60@yahoo.com

    please make sure you contact him for any financial difficulties okay..

    What a powerful man such as DR OTIS DARKO.. he is so much powerful..\\ email him for any difficulties.. otisdarko60@yahoo.com................... YOU CAN ALSO ADD US UP ON WHATSAPP USING THIS MOBILE NUMBER:+2348077526136

    ReplyDelete
  30. Need a spell caster?then think of Dr Otis Darko he is real reliable and he does what he promise you.I know all this because he helped with my marriage problem.For security reason i will not live my name here but i can tell you all he did to help me.Me and my family live in the US military base here in America,my wife is a solider and i love it that she is and i support.But being a solider means she is half my wife and fully the U.S army.before her three tour we were so in love and we had a kid son who we both love him.It all changed after her two tour in Iraq and Afghanistan,i noticed the distance her second tour she stopped call at first i thought maybe she was part of an accident but i found out that she was OK in Afghanistan.She explained that she always on patrol.It got ugly on the third. I guess in the last two tours she found herself a new lover and then totally forgetting me and our boy.I can not say i did not notice because she always has to be some where instead of with me,coming up with some silly excuse not to be with me that is ( have sex ) and her entire behavior told me all i needed to know. i did my research and i had a hint that it was her squad lieutenant. I had know evidence so a could not take the matter to any body.It killed me to seeing this happen i was going suicidal.What hurt me the most was she going home knowing that i suspect she infidelity,she kept lying to me over and over again.The power of positive thinking helped me a lot.I thought that maybe i can find in the help on the internet with the people who had being in the same problem with him.I found a lot of ways but nor worked except Dr Otis Darko spell.At that time five month ago i was so confused that i could do anything to get my wife back so i contacted Dr Otis Darko with his email address i saw in some comment on the internet at otisdarko60@yahoo.com. I laid down my problem to him and told him the entire story and he even confirmed my hint was right, how he did i do not know but he was right because my wife told me later after the spell was made effective. Dr Otis Darko cast a spell on them both do not know what he did but it seem he made them both forget they ever crossed path romantically speaking like they never know each other expect there official relationship that is squad leader and solider.I owe my life to DR OTIS DARKO what he did saved my marriage.I can tell you this because i have tried and it worked for me.Your case also have a solution with Dr Otis Darko contact him with his email otisdarko60@yahoo.com.................... YOU CAN ALSO ADD US UP ON WHATSAPP USING THIS MOBILE NUMBER:+2348077526136

    ReplyDelete
  31. Am just an over exerted today for what this great man call DR ADAGBA of adagbaspiritualtemple@yahoo.com has just done in my marital life, after all the emotional pain that i have being passing through all this years have be turn to joy .and i will like you on this forum to help me in thanking he because for the past two years my husband has been cheating on me with a lady and this has course the family a lot of problems and our baby Evonne where the one perpetual taking the pain because at this time my husband don\'t normally come home to ask after the child or even care about what the child needed so with all this problems i was not happy in my marriage and i started going for different kind of marriage cancelling and looking for solution every where not until this faithful day when i was browsing on the internet i saw a testimony shared by miss Tessy Jerry Uk about this DR ADAGBA and i also contacted him for help and that was how he gave me some instructions and and i followed what ever he told me and i was surprise when he said to me go my child for all will be fine within the next 24 hours .and within the 24 hours i actually received a call from my husband who has not called me for some months now asking after the child and i . and that was how was the end of my marriage problems . so this is why i promise to testify to the whole world about this man DR ADAGBA and if any is also depress with such problems contact him now on:adagbaspiritualtemple@yahoo.com and you will also find success and all your heart desire will be granted by
    DR ADAGBA, of : adagbaspiritualtemple@yahoo.com or http://adagbaspiritualtemple.webs.com/

    ReplyDelete
  32. Am just an over exerted today for what this great man call DR ADAGBA of adagbaspiritualtemple@yahoo.com has just done in my marital life, after all the emotional pain that i have being passing through all this years have be turn to joy .and i will like you on this forum to help me in thanking he because for the past two years my husband has been cheating on me with a lady and this has course the family a lot of problems and our baby Evonne where the one perpetual taking the pain because at this time my husband don\'t normally come home to ask after the child or even care about what the child needed so with all this problems i was not happy in my marriage and i started going for different kind of marriage cancelling and looking for solution every where not until this faithful day when i was browsing on the internet i saw a testimony shared by miss Tessy Jerry Uk about this DR ADAGBA and i also contacted him for help and that was how he gave me some instructions and and i followed what ever he told me and i was surprise when he said to me go my child for all will be fine within the next 24 hours .and within the 24 hours i actually received a call from my husband who has not called me for some months now asking after the child and i . and that was how was the end of my marriage problems . so this is why i promise to testify to the whole world about this man DR ADAGBA and if any is also depress with such problems contact him now on:adagbaspiritualtemple@yahoo.com and you will also find success and all your heart desire will be granted by
    DR ADAGBA, of : adagbaspiritualtemple@yahoo.com or http://adagbaspiritualtemple.webs.com/

    ReplyDelete
  33. Everyone needs to know the great love spell caster Dr Ogudugu I can’t tell how long it took me to find a trust worthy spell caster like Dr Ogudugu online, I am a very satisfied and happy person today. i have used many spell caster but none of them could bring my man back but Dr Ogudugu did. After his spell was done, My lover moved in with me. I want anyone who want his or her lover back to choose Dr Ogudugu for help cuz he is the right choice to go with. his love spell was excellent. call him +2348057266712

    ReplyDelete
  34. My name is Rusty Kate, from UK I never believed in love spells or magic until i met this spell caster once. when i went to Africa in July this year on a business summit. i meet a man called Dr. Erigo.He is powerful he could help you cast a spells to bring back my love?s gone,misbehaving lover looking for some one to love you, bring back lost money and magic money spell or spell for a good job.i?m now happy & a living testimony cos the man i had wanted to marry left me 3 weeks before our wedding and my life was upside down cos our relationship has been on for 2 years? i really loved him, but his mother was against me and he had no good paying job. so when i met this spell caster, i told him what happened and explained the situation of things to him..at first i was undecided,skeptical and doubtful, but i just gave it a try. and in 6 days when i returned to New York, my boyfriend (is now my husband ) he called me by himself and came to me apologizing that everything had been settled with his mom and family and he got a new job interview so we should get married..i didn?t believe it cos the spell caster only asked for my name and my boyfriends name and all i wanted him to do? well we are happily married now and we are expecting our little kid,and my husband also got a new job and our lives became much better. in case anyone needs the spell caster for some help, email;Erigospellcaster@gmail.com you can see what he can do and i believe that he can help you,
    OR you can get more information from me on my Email: blissmichellelorraine@hotmail.com

    ReplyDelete
  35. 100% percent sure! The only person that i can boldly say he can cure any herpes deceased and that can also solve any relationship problem, is this great herbalist man called dr fara after i came in contact with him, thank you dr fara for restoring my relationship back and CURE GENITAL HERPES OUT OF MY BODY you can contact him through his email on: drfaraspelltemple@gmail.com you can call him telephone number:+2348054265852 And get your problems solve like me…..

    ReplyDelete