首页 > 解决方案 > Spring JPA Criteria API 无法访问子类中的属性

问题描述

我有以下课程:(仅显示相关字段)

@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 {

}

我正在尝试选择匹配对象与某些条件匹配的DemoLink实体列表。Demo为此,我想使用规格:

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

但是,当我尝试使用该规范执行查询时,出现以下错误:

无法在此 ManagedType [内容] 上找到具有给定名称 [类型] 的属性

我尝试向 CriteriaBuilder 说明这一点:

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) 
    }
}

不幸的是,这仍然会导致相同的错误。所以,我决定过火,也投了内容关联:

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) 
    }
}

即使这会导致相同的错误。

我究竟做错了什么?

谢谢

标签: spring-bootkotlinspring-data-jpa

解决方案


推荐阅读