Hibernate Native SQL
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Native Joins
- If we would like to get data from both User and team based on the user table, we can use native joins. In this case, we are using the left outer join
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.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import com.tu.hibernate.HibernateUtil;
public class NativeQueryNativeJoin {
static Logger logger = Logger.getLogger(NativeQueryNativeJoin.class.getName());
static String dash = "--------------------------------------------------------------";
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
nativeJoin(session);
} catch (Exception e) {
logger.warning(e.toString());
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
@SuppressWarnings("unchecked")
public static void nativeJoin(Session session) {
// 2.4.1 Native query with JOIN
// }
logger.info(dash);
List<Object[]> user = session.createNativeQuery(""
+ "select u.name, t.team_id from user u left outer join team t on u.team_id=t.team_id where u.user_id=?")
.setParameter(1, 1).list();
user.stream().forEach(objects -> {
String name = (String) objects[0];
int teamId = (int) objects[1];
if (logger.isLoggable(Level.INFO)) {
System.out.println(String.format("Info : User[ %s, %d ]", name, teamId));
}
Press desired key combination and then press ENTER.
1
Press desired key combination and then press ENTER.
- Notice that the returned Object List are the columns requested.
- To ensure eager loading of associated tables we can use addJoin and addEntity.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content