Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring数据JPA条件实体联接_Java_Spring_Jpa_Spring Data Jpa - Fatal编程技术网

Java Spring数据JPA条件实体联接

Java Spring数据JPA条件实体联接,java,spring,jpa,spring-data-jpa,Java,Spring,Jpa,Spring Data Jpa,我有不寻常的表设置,我想在JPA映射。下面是一个简化的示例: book company_id int book_id int series_id int borrow company_id int book_id int type char 问题在于,brook.book\u id过载: 如果borrow.type为“B”,则borrow.book\u id==book.book\u id 如果borrow.type为“S”,则borrow.

我有不寻常的表设置,我想在JPA映射。下面是一个简化的示例:

book
  company_id int
  book_id    int
  series_id  int

borrow
  company_id int
  book_id    int
  type       char
问题在于,brook.book\u id过载:

如果borrow.type为“B”,则borrow.book\u id==book.book\u id 如果borrow.type为“S”,则borrow.book\u id==book.series\u id
从逻辑上讲,这种关系是多借一本书。直接的用例是:获得所有借阅行,并给出一个图书列表。在Spring Data JPA中应该如何映射这一点?

您可以在您的《借阅实体映射》一书中尝试以下内容-

@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")) }
)
但是您需要使用@ManyToOne注释,即使这似乎是一个@OneToOne关联。联接公式在OneTONE上不起作用。 这种方法的缺点是,hibernate将不必要地创建2个连接,而这只能使用1个本地查询来完成

如果您使用的是SpringDataJPA,那么在您的存储库中,您可以使用如下方法-

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

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

您可以在“借阅实体映射”一书中尝试以下操作-

@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")) }
)
但是您需要使用@ManyToOne注释,即使这似乎是一个@OneToOne关联。联接公式在OneTONE上不起作用。 这种方法的缺点是,hibernate将不必要地创建2个连接,而这只能使用1个本地查询来完成

如果您使用的是SpringDataJPA,那么在您的存储库中,您可以使用如下方法-

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

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

您使用的是hibernate吗?可以使用hibernate属性注释吗?@RobertNiestroj我使用的是Spring数据,默认情况下它似乎使用hibernate。不确定Hibernate解决方案是否在此设置中工作,但如果您有,我可以尝试。您正在使用Hibernate吗?可以使用hibernate属性注释吗?@RobertNiestroj我使用的是Spring数据,默认情况下它似乎使用hibernate。不确定Hibernate解决方案是否能在这个设置中工作,但如果您有,我可以试试。