Jackie
Jackie

Reputation: 23607

GORM hasMany using multiple columns

I have a class as follows

class PrefValue extends MainDomain {

    String entityClass
    Long entityId
    ....
}

I am now trying to map a collection to two different classes

class TypeA extends MainDomain {
  Long entityId
  static hasMany = [preferences:PrefValue]
  static mappedBy = [preferences: "entityId"]
  ...
}
class TypeB extends MainDomain {
  Long entityId
  static hasMany = [preferences:PrefValue]
  static mappedBy = [preferences: "entityId"]
}

The problem arises because both TypeA and TypeB can have the same ID but they will have different entityClass values. How would I map this?

Upvotes: 1

Views: 281

Answers (1)

Igor
Igor

Reputation: 34011

I'm assuming that entityId is the primary key, leading to issues when TypeA and TypeB both have the same value for their primary key.

In this case you can drop the primary key constraint and instead use a composite primary key instead. The documentation goes into more detail about it here.

If you it is NOT a primary key and is just has a unique constraint, then you can make the entityId unique per discriminator:

static mapping = { entityId unique: 'entityClass' }

Upvotes: 1

Related Questions