Hibernate Native SQL
vembubalaji
56.6K 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
Mapping Non-managed entities via result transformer
- Until now, we have been mapping result sets to specific entities, what if we want to map the result set directly onto a JavaBean rather than an entity. For this, we can us the Result transformer
- Here again, we have implicit transformer, explicit transformers.
- For Implicit transformation, we would use the Transformers.aliasToBean method. Here the understanding is that the columns returned from the result set have the same naming convention with that of the mapped JavaBean. In this case, the CustomDTO’s attributes.
- In case the columns returned from the result set names does not match the names on the mapped JavaBean attributes, and then we opt for the explicit transformation.
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 org.hibernate.transform.Transformers;
import com.tu.dto.CustomDTO;
import com.tu.dto.MoreCustomDTO;
import com.tu.hibernate.CustomResultTransformer;
import com.tu.hibernate.HibernateUtil;
public class ResutlSetConstructionTransformer {
static Logger logger = Logger.getLogger(ResutlSetConstructionTransformer.class.getName());
static String dash = "--------------------------------------------------------------";
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
transformer(session);
} catch (Exception e) {
logger.warning(e.getMessage());
} finally {
if (session != null) {
session.close();
}
}
HibernateUtil.shutdown();
}
@SuppressWarnings({ "unchecked", "deprecation" })
public static void transformer(Session session) {
// }
List<CustomDTO> custom = session.createNamedQuery("3tableJoin")
.setResultTransformer(Transformers.aliasToBean(CustomDTO.class)).setParameter(1, 1).list();
CustomDTO dto = custom.get(0);
System.out.println("Info: Domain Name from default Result Transformer " + dto.getDomainName());
System.out.println("Info: User Name from default Result Transformer " + dto.getUserName());
System.out.println(dash);
List<MoreCustomDTO> moreCustom = session.createNamedQuery("3tableJoin")
1
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.