Hibernate Native SQL
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Adding joins with entity mapping.
- We can also use addEntity() and addJoin() methods to fetch the data from associated table using tables join. The above query can be re-written as following;
A quick sample. Check out the JAVA class and SQL file
1
41
42
43
44
45
46
47
48
49
50
51
// {
List<Object[]> usersJoin = session
.createNativeQuery(
"select u.*, t.* from user u left outer join team t on u.team_id=t.team_id where u.user_id=?")
.addEntity("u", User.class).addJoin("t", "u.team").setParameter(1, 1).list();
usersJoin.stream().forEach(object -> { // The user's object list would contain a User instance and a
// "joined"
// team instance.
User userJoin = (User) object[0];
logger.info("User - " + userJoin.getName());
logger.info("User Domain - " + userJoin.getDomain().getDomainName());
Enter to Rename, Shift+Enter to Preview
1
Enter to Rename, Shift+Enter to Preview
- Notice the second query, which fetches the Domain details. This is the eager Loading of the requested object
- [aliasname].* is used to return all properties of an entity. When we use addEntity() and addJoin() with join queries like above it returns both the objects, as shown above.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content