Good afternoon,
I was wondering if I should ask here about an issue with a recursive + non-recursive CTE that seems to work correctly when using MySQL as the datasource but not H2?
I didn’t want to assume it was a Hibernate issue when building the query for a specific technology (H2) vs if H2 can actually do the query.
I can try and produce a minimal working example if its appropriate here but basically I have used the “raw sql” outputted by the logs and it seems to not work in H2 but does work fine in MySQL ( just had to replace the FETCH FIRST
with LIMIT 1
to get it to work for MySQL).
Its basically a hierarchical recursive query/cte, then another cte that uses the initial cte results but then orders them and limits to 1 to try get a “maximum hierarchical level” row.
A User
has a parent User
: ManyToOne
User:User (User to Parent)
A User
has an optional Wallet
. OneToOne(optional)
Wallet:User
Using the @MapsId
so the Wallet ID (if the user has one) is the same as the User ID.
The query below is to find a users tree (from bottom to top), then find the wallets in that tree of users. The wallet that is “closest” to the root User (:rootUserId) is the one to find (so note the order by hlevel ASC limit 1
PSUEDO:
with user_hierarchy_cte (
select u.id as userId, u.parent.id as parentId, 0 as hlevel
from User u
where u.id = :rootUserId
union all
select u.id as userId, u.parent.id as parentId, uhcte.hlevel + 1 as hlevel
from User u
join user_hierarchy_cte uhcte on u.id = uhcte.parentId
),
nearest_account_cte as (
select w.id as walletId ,w.credit as credits, uhcte.hlevel as `level`
from Wallet w
join user_hierarchy_cte uhcte on uhcte.accountId = w.id
order by hlevel ASC
limit 1
)
select wcte.walletId as walletId, wcte.credits as credits
from nearest_account_cte wcte
Thank you for any guidance.