John R
John R

Reputation: 95

What is the correct Grails ORM (GORM) implementation to use?

As a result of a change request I need to implement the correct ORM for my Grails application.

I currently have the following simple models and associations:

However, now I need to implement the ability for a single Fee to be split amongst Agents. I ended up with the following:

Potential new models associations

In my mind an AgentFee would contain:

So my question is. Should I also have an association between Agents and AgentFees i.e. something like:

But this just feels wrong with the multiple belongsTo in AgentFee. What is the best way to implement the notion of "Fee Splits" using GORM?

Thanks in advance,

John

Upvotes: 0

Views: 174

Answers (2)

Kamil Mikolajczyk
Kamil Mikolajczyk

Reputation: 911

answering questions from comments:

@Michael @John if you look at the underlying database tables then you'll see only a foreign key from one table to another, tables do not cross reference unless it's one-to-one, so simplifying the domain classes like I described earlier changes nothing in physical data and it's easier to maintain in your code (you don't have to use addTo() and removeFrom methods), you just create a dependent object and set it's reference to current (you always change only one thing)

Agent a = new Agent()
Fee fee = new Fee(

also, if you want to retrieve all related objects, you can create a property returning list like

class Fee {
    Agent agent
}
class Agent {
    List<Fee> getFees() { 
        Fee.findAllByAgent(this) 
    }
}

and use it like

Agent a = new Agent()
List<Fee> aAgentsFees = a.fees

of course it's read only, and if you want to create them:

Agent agent1 = new Agent()
Fee feeA = new Fee(agent: agent1)
Fee feeB = new Fee()
feeB.agent = agent1

Upvotes: 0

Michael
Michael

Reputation: 2726

It sounds like you are changing the relationship to a many-to-many. Here is the documentation for that: http://grails.github.io/grails-doc/latest/guide/GORM.html#manyToMany

A many-to-many relationship needs a joining table at the DB level. However, you most likely don't need a domain for your joining table i.e. you don't need AgentFee. GORM will know to use a joining table.

The only time you need a domain object for your joining table is if the joining table has additional columns beyond the ones needed to facilitate the many-to-many relationship. In this case you would create a domain for the joining table and then create two one-to-many relationships, one in each direction.

Upvotes: 1

Related Questions