Hibernate Native SQL
vembubalaji
56.4K views
01 Hibernate Native SQL
Hibernate Native SQL - Introduction Use parameter binding in native SQL queries Adding scalars Native Joins Adding joins with entity mapping Basic Result set mapping using @SqlResultSetMapping Mapping Non-managed entities via result transformer Mapping Non-managed entities via result Custom Transformer
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// {
package com.tu.nativesqlsample;
import java.util.List;
import java.util.logging.Logger;
import org.hibernate.Session;
import com.tu.hibernate.HibernateUtil;
import com.tu.hibernate.entity.Team;
import com.tu.hibernate.entity.User;
public class NativeQueryNativeJoinWithEntity {
static Logger logger = Logger.getLogger(NativeQueryNativeJoinWithEntity.class.getName());
static String dash = "--------------------------------------------------------------";
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
// Mapping Native JOIN query to Entities
nativeJoinWithEntity(session);
} catch (Exception e) {
logger.warning(e.toString());
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
@SuppressWarnings("unchecked")
public static void nativeJoinWithEntity(Session session) {
logger.info(dash);
// }
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());
1
- 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.
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.