I am accesing to the database using a Dto with some entities and I want to improve the request without modifing my dto and removing the fetch so hibernate don´t return all the data from all the entities (hibernate is set to lazy), I tried with the next, but it´s not working:
StringBuilder hql = new StringBuilder();
hql.append(" select d.id as id, ce.cod as clasification.cod ");
hql.append(" from Document d");
hql.append(" join d.clasificacionEntity ce");
The working hql request:
StringBuilder hql = new StringBuilder();
hql.append(" select d");
hql.append(" from Document d");
hql.append(" join fetch d.clasificacionEntity ce");
The problem is when I try to use "ce.cod as clasification.cod" the second dot gives me a error, there is other way to do that? , thanks a lot!!!
My dto result is:
DocumentDto{
private id
private clasificacionEntityDto;
}
And
clasificacionEntityDto {
private cod
}
When you write this code:
hql.append(" select d.id as id, ce.cod as clasification.cod ");
You tell on parser d.id
named id
and ce.cod
named clasification.cod
The last alias is wrong! A correct name is clasification
or cod
.
If you want to point properties of ce.cod (cod which data type has?) you can point after extraction of your result.
You don't mention how you are transforming the query result into your DTO entities. One simple solution that does not require you to alter your DTO classes.
// select only the fields you need from your query
StringBuilder hql = new StringBuilder();
hql.append(" select d.id as id, ce.cod as cod ");
hql.append(" from Document d");
hql.append(" join d.clasificacionEntity ce");
// ... etc. Then get back your results as raw type
List<Object[]> rows = crit.list();
Then loop through your results and create your DTOs manually. Note that this example assumes that your document has a single classification.
List<DocumentDTO> documents = new ArrayList<DocumentDTO>();
for ( Object[] row: rows ) {
Long id = (Long)row[0];
String cod = (String)row[1];
ClassificationEntityDTO ce = new ClassificationEntityDTO(cod);
DocumentDTO d = new DocumentDTO(id, ce);
documents.add(d);
}
See this question
AliasToBeanResultTransformer(MyDTO.class) fails to instantiate MyDTO
At the end I just create a dto like this:
DocumentDto{
private id
private String clasificacionEntityDtoCod;
}
and set it like this:
StringBuilder hql = new StringBuilder();
hql.append(" select d.id as id, ce.cod as clasificacionEntityDtoCod ");
hql.append(" from Document d");
hql.append(" join d.clasificacionEntity ce");