how to create a reference relationship in groovy domains? - grails

i just wanted to make a drop down box appear on the view page of my main domain.
I tried doing
static hasOne = [sex: Sex, accountType: accountType]
and I did this on the main domain but it would give me an error that the domains I wanted to have a reference with are not bidirectional. so i just tried to put a reference on the reference domains of my main domain which now made the reference domain like the accountType have a field of a specific.
I was wondering how can I just make it like a one way reference?

To make it a one-way reference, don't use the hasOne connection.
So, your class would look like this instead:
class MyClass {
Sex sex
AccountType accountType
}
hasOne and it's brethren indicate who "owns" a bi-directional relationship, so if you are only going one way, you don't need to use them.

Related

Grails: Simple hasMany relation create more tables than necessary

Hi I have a simple problem.
My domain class is like this:
class Example {
long seq
hasMany = [example_array: ExampleData]
long count
}
class ExampleData {
String type
long description
static belongsTo = Example
static constraints = {
}
}
This results in 3 tables, like a many to many relation.
Why is this?
Thanks
The reason for the extra table is that you've modeled the relation only in one direction - an Example can access its ExampleData instances via the example_array Set that's added to your class bytecode because of the hasMany property, but an ExampleData instance has no way to reference its owning Example.
You added a belongsTo property, but only specified the class name. That's sufficient to configure ownership, cascaded deletes, etc. but doesn't provide a property in the class to access the Example instance.
If you change it to the other supported syntax it will work as you expected:
static belongsTo = [example: Example]
Here example will end up being the name of an Example property (and you can change it and/or example_array to any valid property name), which is basically the same as declaring
Example example
Now that both sides can access the other, the relationship is bidirectional and you no longer need the third table. That's because a 1-many is typically implemented using a foreign key in the child table, in this case in the table for ExampleData that points to the table for Example. That wasn't possible without a property in the class to wire up to that column, so the join table was necessary.
I believe that you have to map the BelongsTo, like this:
static belongsTo = [example:Example]
Hope it helps :)
From the definition of hasMany Grails will, by default, map this kind of relationship with a join table.That join table is the 3rd table you mentioned.No need to worry about that.
Well the one-to-many relationship is constructed by having additional table (i.e. Example_ExampleData) containing two columns each id fields from tables of the entities forming the relationship(i.e. Example and ExampleData).
The newly added table is child to parent tables – Example and ExampleData.
So in your case when you run your application the 3rd table gets created by Grails by default as your table relationship falls under the one-to-many relationship.

Grails belongsTo relationship mechanism

In a Grails relationship when an Owner domain class owns an Owned domain class, I've seen this declared two different ways in the Owned domain class:
static belongsTo [ owner : Owner ]
and sometimes as
static belongsTo [ Owner ]
what is the difference between these two other than the syntax?
The difference is being able to indicate the name of the owned by property. In the second case it's going to assume the bean name convention of the class owner where as the first you are being explicit about the name of the property.
It's about flexibility. The first option is there if the second doesn't do what you intend or want.
The first is bidirectional, since you have an instance of Owner defined in your class. The key of that map is typically the lowercase name of the domain class, but it can be any legal variable name. An AST transformation adds a property to your domain class (you can see this by decompiling the .class file), basically
Owner owner
or
Owner theOwner
if you had declared the belongsTo as
static belongsTo = [theOwner: Owner]
Don't add this yourself though - it's already there in the bytecode.
This is similar to declaring a hasMany, where the key of that map defines a collection (by default a Set but optionally a List). E.g. declaring
static hasMany = [owned: Owned]
creates the equivalent of
Set<Owned> owned
in the bytecode.
The second isn't bidirectional since there's no direct way to get to the owning instance.
Directionality has an impact on the table structure. In the first, you get what you probably expect - an owner_id column in the Owned domain class table which is a foreign key to the Owner domain class table. But in the second, there isn't a domain class property to associate with a foreign key, so in that case a third table is created to be the join table, similar to what happens for a many-to-many relationship.
I find that the schema-export script is very helpful for stuff like this. For each variant of the syntax, run
grails compile
grails schema-export
and view the contents of target/ddl.sql to see the resulting table structure for your domain classes.
it's as simple as that:
if you define the
static belongsTo = [ owner : Owner ]
then you can can access the owner as a variable: obj.owner. If you write:
static belongsTo = [ Owner ]
then you can't (you will get NoSuchPropException I guess).
In both cases the foreign-key relation is created

How to make a domain class that belongs to one of a number of possible classes in Grails

I want to create a Comment class to allow my users to add comments to a number of different things.
class Comment {
User author
String text
static belongsTo = [post:Post, user:User]
static contraints= {
post(nullable:true)
user(nullable:true)
}
}
When I try and create a comment object using a post and without a user, i get the error "Property [user] of class [class Comment] cannot be null".
What is the best way to create a class that can belong to one of a number of different classes?
The best solution is to use a plugin like commentable.
However, if you want to roll your own solution then you need to understand that making something BelongTo another object makes it a required relationship. Thus it can't be null. Remove the belongs to and do a uni-directional one-to-many relationship. See the Grails documentation on modeling relationships.

One-to-many relationship not working as expected

I'm having some problems getting a one to many relationship in grails working properly.
I have a person instance and this person has relationships to other persons. This relationship is defined in a relationship object.
The relevant code is as follows.
class Person {
static hasMany = [relationships:Relationship]
String name
}
class Relationship {
Person relationShipTo
// Enum containing married, living together, parent etc.
RelationshipType typeOfRelationship
}
Now what i want is a one to many reference to that relationship to be persisted but what happens in grails is that it seems to think the relationShipTo instance is refering back to the Person that has this relationship with someone else, and not to the other person.
So a person has a reference to a relationship, and that relationship has a type and a reference to the person with whom you have a relationship with.
I'm not able to change the domain model for this. Is there any way of accomplishing what i want?
What is currently happening if i use the generated views and controllers for the Relationship and try to create a relationship with a type and a person it is refering to, only the type is persisted and the person is ignored. When i then try to add it to the person in the persons edit or create page, all the relationShipTo properties of the relationships i add is saved with the id of the person.
Hopefully what i wrote is understandable.
Finally got it working.
Had to add a static mappedBy =[relationship: 'belongsTo'] to person
and a static belongsTo = [belongsTo: Person].
Not exactly how i wanted it but it works and is an ok compromise

Grails: Collection in domain object without hasMany

I have two domain objects A and B.
A can be associated with many Bs but I do not want any save cascade from A to B.
I'm thinking of defining the hasMany relationship form A to B, but then setting a cascade behavior. Any ideas?
This is an example of my domain objects:
class A{
static hasMany = [bees:B]
}
class B{
}
If you do not wish for GORM to manage the save/updates for your collection simply don't use hasMany. Instead treat it as a simple HashSet property.
Why not use 'belongsTo' on B, and don't declare anything on A? This way you'll get the foreign key to 'A', but operations on 'A' won't affect 'B'. You lose a bit of convenience, but can still easily look up all 'B' by 'A'. I actually prefer this because I don't need to worry about lazy loading gotchas and hibernate going and loading all the 'B's when I'm just trying to add one (assuming you don't need that functionality).
class A{}
class B{
static belongsTo = [your_a:A]
}
//get your B's for a given A
B.findAllByA(your_A_instance, ...paging, etc...)
You can define your own cascading behavior in the static mappings block of your Domain class.
See here: http://grails.org/doc/latest/ref/Database%20Mapping/cascade.html
If you are saying what I think your are saying then what you are talking about is not cascading. A simple outline of your classes would be helpful. If you have an instance of A which is associated with many instances of B, then all instance of B which reference the instance of A in question are referencing the exact same object. I had the same problem and asked a similar question here. Basically your options are:
1.) Clone the instance of A whenever it changes or whenever you deem appropriate.
2.) Create new fields in your B class which will hold the values of A you are concerned with.
Both approaches have their advantages and disadvantages, but for me option 2 proved to be the better choice.

Resources