I recently dig into Hibernate and found two ways to do an inner join query using HQL, but I don't know what's the difference between them and which one to use.
Let's assume that we have two tables:
Table user
+-------+-----------+-----------+
|userId |userName | userLevel |
+-------+-----------+-----------+
|1001 |James | 0 |
+-------+-----------+-----------+
|1002 |Tom | 2 |
+-------+-----------+-----------+
Table order
+----------+-----------+-----------+----------+
|orderId |userId |productId |fee |
+----------+-----------+-----------+----------+
|1001 |1002 |1003 | 5 |
+----------+-----------+-----------+----------+
|1002 |1002 |1005 | 50 |
+----------+-----------+-----------+----------+
|1003 |1001 |1010 | 30 |
+----------+-----------+-----------+----------+
User Tom could have multi order records in the order
table. And here comes a demand that we want to find some the order information of Tom alone with his name, if it is raw sql
we could do this:
select user.userId, user.userName, order.orderId, order.fee from user join order where user.userId=order.userId and user.userId=1002;
But on coming to hibernate I found two ways that could achieve this:
using the
one-to-many
mapping to connect the relation between user and order and make aorderEntities<Set>
in theuserEntity
definition then make a HQL query like this:FROM UserEntity as U INNER JOIN U.orderEntities as O WHERE U.userId=1002;
Or
omit the
one-to-many
definition and just make a HQL query like this:FROM UserEntity U, OrderEntity O WHERE U.userId = O.userId AND U.userId=1002;
What's the different between these two ways of querying? And which one should I use?