I am working on a spring boot project and using JPA for querying the database with Entity manager.
i.e.
Query query = entityManager.createNativeQuery("SELECT * FROM TABLE_NAME WHERE ID = 1"); // SUPPOSE
List<Object[]> result = (List<Object[]>) query.getResultList();
now after this what I want to achieve here is creating an Object of that corresponding result.
i.e. ResultObject obj = (ResultObject) result.get(0);
// here ResultObject is user defined.
but this type of casting is not possible directly.
so what I am currently doing is:
ResultObject obj = new ResultObject();
obj.setArribute1((String) obj[0]);
obj.setArribute2((Integer) obj[1]);
...
and on average i will be having 15 attributes per object. so its really tiresome...
I have tried using:
List<ResultObject> obj = (List<ResultObject>)query.getResultList();
but doesn't work.
Either use ConstructorResult (JPA) or ResultTransformer (Hibernate) or QLRM.
ConstructorResult is JPA standard and you have to create a Annotation with the column mapping:
@SqlResultSetMapping(
name = "BookValueMapping",
classes = @ConstructorResult(
targetClass = BookValue.class,
columns = {
@ColumnResult(name = "id", type = Long.class),
@ColumnResult(name = "title"),
@ColumnResult(name = "version", type = Long.class),
@ColumnResult(name = "authorName")}))
From https://thorben-janssen.com/result-set-mapping-constructor-result-mappings/
And ResultTransformer is Hibernate proprietary and you must use the Hibernate session:
List<PersonSummaryDTO> dtos = session.createNativeQuery(
"SELECT p.id as \"id\", p.name as \"name\" " +
"FROM Person p")
.setResultTransformer( Transformers.aliasToBean( PersonSummaryDTO.class ) )
.list();
Or QLRM is a library that maps the result to a DTO using the constructor:
JpaResultMapper jpaResultMapper = new JpaResultMapper();
Query q = em.createNativeQuery("SELECT ID, NAME FROM EMPLOYEE");
List<EmployeeTO> list = jpaResultMapper.list(q, EmployeeTO.class);