Spring Data JPA条件实体联接

起飞:

我有要在JPA中映射的不寻常的表设置。这是一个简化的示例:

book
  company_id int
  book_id    int
  series_id  int

borrow
  company_id int
  book_id    int
  type       char

问题borrow.book_id是超载的:

  • 如果borrow.type是“ B”,则borrow.book_id == book.book_id
  • 如果borrow.type是“ S”,则borrow.book_id == book.series_id

关系在逻辑上是许多borrow到一个book直接的用例是:给所有borrow行指定books 的列表在Spring Data JPA中应如何映射?

dexter_:

您可以在Book的借阅实体映射中尝试以下操作-

@ManyToOne
@JoinColumnsOrFormulas(
    { @JoinColumnOrFormula(
        formula = @JoinFormula(
         value = "case " +
                 "when type == 'B' then book_id" +
                 "when type == 'S' then series_id " +
                 "else 1" +
                 "end", 
         referencedColumnName="book_id")) }
)

但是,即使这似乎是@OneToOne关联,也需要使用@ManyToOne批注。加入公式不适用于OneToOne。这种方法的缺点是,hibernate会不必要地创建2个连接,而使用本机查询只能使用1个连接来完成

如果您使用的是Spring Data JPA,则可以在存储库中使用类似-

@Query(value="sql stmt with conditional join and IN clause", nativeQuery = true)
List<Idto> findAllBorrowByBook(List<int> bookIds);

其中“ Idto”是映射结果集的接口。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章