Spring JPA Criteria API can't access properties in sub class

Viewed 190

I have the following classes: (Only relevant fields shown)

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class Content {
  
}

@Entity
class Demo : Content {
  var key: String
}

@Entity(name = "contentlink")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
class ContentLink {
    @ManyToOne
    @JoinColumn(name = "content_id")
    internal var content: Content
}

@Entity
class DemoLink : ContentLink {

}

I'm trying to select a list of DemoLink entities for which the matching Demo object matches some criteria. For this, I want to use Specifications:

fun hasType(type: String): Specification<DemoLink> {
    return Specification { root, _, cb -> 
        cb.equal(root.get<Demo>("content").get<String>("type"), type) 
    }
}

However, when I try to execute a query with that specification, I get the following error:

Unable to locate Attribute with the the given name [type] on this ManagedType [Content]

I tried instructing the CriteriaBuilder about this:

fun hasType(type: String): Specification<DemoLink> {
    return Specification { root, _, cb -> 
        cb.equal(cb.treat(root, DemoLink::class.java).get<Demo>("content").get<String>("type"), type) 
    }
}

Unfortunately, this still results in the same error. So, I decided to go overboard and also cast the content association:

fun hasType(type: String): Specification<DemoLink> {
    return Specification { root, _, cb -> 
        val link = cb.treat(root, DemoLink::class.java)
        val demo = cb.treat(link.get("content"), Demo::class.java)
        cb.equal(demo.get<String>("type"), type) 
    }
}

Even this results in the same error.

What am I doing wrong?

Thanks

0 Answers
Related