简体   繁体   English

Spring Data JPA 条件实体加入

[英]Spring Data JPA conditional entity join

I have unusual table setup that I want mapped in JPA.我想在 JPA 中映射不寻常的表设置。 Here's a simplified example:这是一个简化的示例:

book
  company_id int
  book_id    int
  series_id  int

borrow
  company_id int
  book_id    int
  type       char

The problem is borrow.book_id is overloaded:问题是borrow.book_id超载了:

  • If borrow.type is 'B', then borrow.book_id == book.book_id如果borrow.type是'B',那么borrow.book_id == book.book_id
  • If borrow.type is 'S', then borrow.book_id == book.series_id如果borrow.type是'S',则borrow.book_id == book.series_id

The relation is logically many borrow to one book .逻辑上多borrowbook的关系。 The immediate use case is: get all borrow rows given a list of book s.直接用例是:在给定book列表的情况下获取所有borrow行。 How should this be mapped in Spring Data JPA?这应该如何在 Spring Data JPA 中映射?

You can try something like below in your Borrow entity mapping for Book -您可以在 Book 的 Borrow 实体映射中尝试以下操作 -

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

But you need to use the @ManyToOne annotation, even though this seems to be a @OneToOne association.但是您需要使用@ManyToOne 注释,即使这似乎是一个@OneToOne 关联。 The join formula won't work on OneToOne.联接公式不适用于 OneToOne。 The downside with this approach would be, hibernate will unnecessarily create 2 joins which could be done using only 1 using a native query这种方法的缺点是,hibernate 将不必要地创建 2 个连接,这些连接可以使用本机查询仅使用 1 个来完成

If you are using spring data JPA then in your repository you could use method like -如果您使用的是弹簧数据 JPA,那么在您的存储库中,您可以使用以下方法 -

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

where "Idto" is an interface to map your resultset.其中“Idto”是映射结果集的接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM