Hibernate Native SQL
vembubalaji
59.5K 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
Basic Result set mapping using @SqlResultSetMapping
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;
import com.tu.hibernate.entity.Domain;
public class ResutlSetConstructionSqlResultSetMapping {
static Logger logger = Logger.getLogger(ResutlSetConstructionSqlResultSetMapping.class.getName());
static String dash = "--------------------------------------------------------------";
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
sqlResultSetMapping(session);
} catch (Exception e) {
logger.warning(e.getMessage());
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
@SuppressWarnings({ "unchecked" })
public static void sqlResultSetMapping(Session session) {
// 2.5.2 - basic Result set mapping using @SqlResultSetMapping
// }
List<Domain> results = session
.createNativeQuery("SELECT domain_id as id, domainName as name FROM domain", "DomainResult")
.getResultList();
results.stream().forEach(result -> {
System.out.println((String.format("Info : team[ %d, %s ]", result.getDomainId(), result.getDomainName())));
});
}
}
1
1
package com.tu.hibernate.entity;
- If the column names of the query result does not match the column names of the entity mapping, then we would have to map the two manually. We can do this using the @SqlResultSetmapping, which specifies the mapping for each attribute.
- As we can see from the above code, the @SqlResultSetMapping constitutes of a name attribute and a @EntityResult annotation that defines the mapping to the entity.
- Now, we need to specify the class of the entity and a set of @FieldResult annotation that defines the mapping between the result set column and the entity attribute.
- To utilize this mapping in the createNativeQuery method we can provide its name as the second parameter. Check the above code snip.
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.