我有要在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
行指定book
s 的列表。在Spring Data JPA中应如何映射?
您可以在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] 删除。
我来说两句