微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Micronaut 数据 JDBC 嵌套实体

如何解决Micronaut 数据 JDBC 嵌套实体

我一直在研究使用 Micronaut 数据 JDBC 作为现有 jdbi 查询的增强。是否可以嵌套 MappedEntity 并返回子项?

示例是具有关系的简单仓库管理系统:

company
+- warehouse
   +- inventory

我想要做的是从 inventory 表向上查询获取 warehouse 的父级和 company 的祖父级。这是一对多的关系,一个公司可以有多个仓库,一个仓库可以有多个库存。

我的实体看起来像

我一直在玩的示例项目位于 wms-api

@JdbcRepository
interface CompanyRepository : PageableRepository<Company,UUID>


@MappedEntity
data class Company(

   @field:Id
   @field:GeneratedValue
   var id: UUID? = null,@field:GeneratedValue
   var timeCreated: OffsetDateTime? = null,@field:GeneratedValue
   var timeUpdated: OffsetDateTime? = null,var name: String
)
@JdbcRepository
interface WarehouseRepository : GenericRepository<Warehouse,UUID> { // used GenericRepository to allow the mapping of Company

   @Join(value = "company")
   fun findById(id: UUID): Warehouse?

   @Join(value = "company")
   fun findByCompany(company: Company,pageable: Pageable): Slice<Warehouse>

   @Join(value = "company")
   fun findAllByCompany(company: Company,pageable: Pageable): Slice<Warehouse>

   @Join(value = "company")
   fun existsByLocationAndCompany(location: String,company: Company): Boolean

   fun save(warehouse: Warehouse): Warehouse

   fun update(warehouse: Warehouse): Warehouse
}

@MappedEntity
data class Warehouse(

   @field:Id @field:GeneratedValue
   var id: UUID? = null,var location: String,@field:Relation(value = MANY_TO_ONE)
   var company: Company
)
@JdbcRepository
interface InventoryRepository : GenericRepository<Inventory,UUID> {

   fun save(inventory: Inventory): Inventory

   @Join(value = "warehouse")
   // FIXME need some way to tell repo to also pull company which is attached to warehouse
   fun findById(id: UUID): Inventory?

}

@MappedEntity
data class Inventory(

   @field:Id
   @field:GeneratedValue
   var id: UUID? = null,var manufacturer: String,var barcode: String,var name: String,@field:Relation(value = MANY_TO_ONE)  // FIXME the problem is caused by this.
   var warehouse: Warehouse,)

堆栈跟踪的相关部分

Caused by: io.micronaut.core.reflect.exception.InstantiationException: Null argument specified for [company]. If this argument is allowed to be null annotate it with @Nullable
    at io.micronaut.core.beans.AbstractBeanIntrospection.instantiate(AbstractBeanIntrospection.java:121)
    at io.micronaut.core.beans.BeanIntrospection.instantiate(BeanIntrospection.java:81)
    at io.micronaut.data.runtime.mapper.sql.sqlResultEntityTypeMapper.readEntity(sqlResultEntityTypeMapper.java:345)

如果可能,我不想让 Warehouse.company 属性成为可选属性

链接的项目中,有一个 docker-compose.yml 支持,可用于启动 Postgres 然后运行测试套件,问题应该会弹出为失败。

谢谢!

解决方法

想通了。必须将 InventoryRepository 的 findById 方法更改为

@JoinSpecifications(
   Join(value = "warehouse"),Join(value = "warehouse.company")
)
fun findById(id: UUID): Inventory?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。