|
我想通过注释@Query通过Jpa存储库进行Join查询。我有三个表。
' A, a* v( C' c7 o3 V1 E3 J- P本机查询是:2 u) Q, N3 e* d M9 }
select application.APP_ID 5 I1 z7 ?4 c# T) v. s9 S. k
from user, customer, application
Q( b0 ]8 B$ rwhere user.USE_CUSTOMER_ID = customer.CUS_ID
8 ~1 [4 }4 j" m! D5 eand application.APP_CUSTOMER_ID = customer.CUS_ID " b! I4 H3 l. B3 x5 J& s
and user.USE_ID=1;5 k2 o# O: z! V. R( w/ ^
现在我有了Table Hibernate实体,所以我在ApplicationRepository中尝试过5 P, q4 N( \2 K1 M: q
@Query(SELECT application FROM Application a! \: I/ o N+ i0 T3 v$ X7 i! P5 u: E
INNER JOIN customer c ON c.customer.id = a.customer.id 0 r* c- X6 L' v& V6 z, x$ S
INNER JOIN user u ON u.customer.id = c.customer.id
' m2 ]# i) w: w5 S INNER JOIN application a ON a.user.id = u.id
H; A) A$ w1 B: e) o% d WHERE+ b; ?' a. t3 \! }) w- `: w$ k
u.id = :user.id)" E+ a3 `9 }) l: J# W3 L- U- ^ F
List findApplicationsByUser(@Param("User") User user);
! C( e k" q& R# `日志说
/ H$ V h& d! U4 s D
, J! H& \4 R/ P y# O+ [意外的标记; N. ^% k2 L1 B/ ], p9 Z7 W% @
* b1 ^5 C' _. L* \1 n
有什么想法吗?% a1 G2 n: W: A* S) w8 `6 B
我的表实体. S, I& M0 `5 o @: P! i
Application.java:: k+ S$ j |/ X6 Y4 G& L* m
@Entity q% a. s7 i. l" x
@Table
, X' ^$ M# \8 ~2 Zpublic class Application extends BaseSimpleEntity {
8 j4 J( f# X& R: Z/ o...& ^: S v5 }# H5 v9 ]; m- E
@ManyToOne(optional = false)" f, U8 Q$ @" V8 h2 Z
private Customer customer;1 B: g6 O! @/ ?7 W$ H, o# y
.... a) J) t! T+ h j
}
, P3 E7 `. s9 V- ?2 KCustomer.java:9 h8 _5 m$ Y7 R" z8 l
@Entity
8 y8 X# ?: z* O8 i@Table
' N2 K4 ~* K+ b n4 Q# A k1 I# Wpublic class Customer extends BaseSimpleEntity {
9 E* C6 X$ g/ e6 G2 t6 p, |; s...
. L2 D6 `9 @7 x9 ` @OneToMany(mappedBy = "customer"), f' r& v# i' `! ` b' J7 |* S
private List[U] users;; y, h. }# n3 l
@OneToMany(mappedBy = "customer")8 C7 U' H6 p7 A8 E: s) Q
private List applications;
, H9 B8 h) t3 M9 L/ i+ \ Q...) n9 x: K' Y$ d! {5 e4 O) y
}
! ?1 s0 ?. \0 E+ t! Y' hUser.java:, P" X9 O0 T- u& d' }: F
@Entity z. }- @" E2 i& \1 d& V* j
@Table
5 E s4 E% ]7 b. V2 kpublic class User extends BaseSimpleEntity {
) P, o4 C+ q. j* f) t7 y% L8 M...
8 N# q, X6 J% P# K; Z @ManyToOne(optional = false); \, b, K3 i# K+ e/ f5 S1 N
private Customer customer;
$ t8 K+ o+ V8 _4 z...
+ R6 S- q5 s/ }- n1 Y}
& z) j# @5 A% l! {$ l0 }' I 8 d+ r* q. E8 y" y, s2 H& m
解决方案:2 n# {1 e2 V6 a% l, E
2 z, G2 H0 b2 W, @) Z
1 B& Q1 k/ p% ~9 ^7 a
. ?+ F/ I. W$ }& x U 您不需要JPA中的ON子句,因为借助映射注释,JPA已经知道如何关联实体。
7 G$ A4 ^% l! b1 p# m6 M此外,您选择的application不是查询中定义的别名。
5 f# _3 A0 P. L, j& N i, R2 V: t您的加入毫无意义。
/ m' h% q9 X# L# q查询应该只是
% s3 z- j- o0 ?( H0 E H2 ?( Fselect application FROM Application a; Y) l( u# ^& x C2 a
join a.customer c . ~" s" l+ S" ~& r% ^9 M5 @% T
join c.users u7 V% M: H3 V: z7 b, }2 d' d
where u.id = :userId
& M' `) Q& G+ w1 u$ y$ T阅读Hibernate文档以了解HQL和联接的工作方式。 |
|