apache / apache/grails-core

namedQueries doesn't work with STI

Open
#14,665 0 comments 0 reactions 0 assignees View on GitHub
relates-to: grails-data-hibernate5
Dominant language
Groovy
Stars
2.9k
Forks
975
Avg merge
1d 22h
Merged PRs (30d)
92

Description

I have a hierarchy with STI:

``` groovy
class Entity {
static namedQueries = {
notDeleted {
}
}

class ConcreteEntity extends Entity {
}
```

When I'm calling `ConcreteEntity.notDeleted.list()` it returns both `Entity` and `ConcreteEntity` instances, but when I'm calling `ConcreteEntity.findAllWhere(...)` it returns only `ConcreteEntity` instances as expected.

I did some investigation for this problem (Grails 2.5.1, grails-datastore-gorm-hibernate-core 3.1.5) and found it adds named query methods for `ConcreteEntity` twice. First time in right context (domainClass == ConcreteEntiy) when it collecting all `namedQueries` closures from current Entity and its hierarchy. Second time in wrong context (domainClass == ConcreteEntity), when collecting `classesToAugment` in HibernateNamedQueriesBuilder. It adds the domainClass itself and all sub classes (including `ConcreteEntity`). So it overwrites ConcreteEntity.notDeleted method with closure for `ConcreteEntity` with new closure for `Entity`.

I monkey patched with `metaClass` method from `HibernateNamedQueriesBuilder` and now it works as expected:

``` groovy
HibernateNamedQueriesBuilder.metaClass.getClassesToAugment = {
return [domainClass]
}
```

Contributor guide

Open the contributing guide

Research direction

Start with HibernateNamedQueriesBuilder.getClassesToAugment and the named-query augmentation path described in the issue, using the Grails 2.5.1 and grails-datastore-gorm-hibernate-core 3.1.5 context. Reproduce the ConcreteEntity.notDeleted.list() behavior with STI and compare it with findAllWhere(...). Done means the named query returns only ConcreteEntity instances, without the monkey patch.

Written by the indexing model from the issue text.

Assessment

Tech stack
groovy
Domain
backend, databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.