I want to use Hibernate Transformation with Spring Data.
I have an entity AgentRecord
with attributes as
@Entity
public class AgentRecord extends AbstractEntity<Long> {
@ManyToOne
private User processedBy;
private String description;
private RecordType recordType;
private AgentRecordStatus status;
}
I am following the practice of setting required attributes to a different DTO called AgentRecordDTO
and return it to Client-side(gwt
).
public class AgentRecordDTO implements IsSerializable {
private long processedBy;
private String description;
private RecordType recordType;
private AgentRecordStatus status;
}
Instead of fetching all attributes of an entity, I want to fetch few attributes and set them to AgentRecordDTO
like that of new AgentRecordDTO()
I can do in hql, BUT want to do with Spring Data Specification.
My AgentRepository
is
public interface AgentRecordRepository extends CrudRepository<AgentRecord, Long>, JpaSpecificationExecutor<AgentRecord> {
}
public Page<AgentRecordDTO> getAgentRecords(final long userId) {
SimplePageable page = new SimplePageable(1, 10); //my custom object
Page<AgentRecord> pages = agentRecordRepository.findAll(new Specification<AgentRecord>() {
@Override
public Predicate toPredicate(Root<AgentRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//Projection plus Transformers.aliasToBean(AgentRecordDTO) missing here
Predicate predicate = cb.equal(root.get("processedBy").get("id"), userId);
if (null != predicate) {
predicate = cb.or(predicate, cb.equal(root.get("recordType"), RecordType.VERIFICATION_REQUEST));
predicate = cb.or(predicate, cb.equal(root.get("recordType"), RecordType.VERIFICATION));
}
return predicate;
}
}, new PageRequest(page.getPage(), page.getSize(), new Sort(new Order(Direction.DESC, "id"))));
return null;
}
Hibernate 3.2: Transformers for HQL and SQL dated 03 Jun 2008 was the brilliant post, but
Not a direct answer, but a circumvention..
Whenever Spring Data repository did not match my requirements I resorted to going straight into Hibernate from the entitymanager instead.
e.g.
entityManager.unwrap(Session.class).
createSQLQuery(SPECIAL_QUERY).
setTimestamp("requestTime", time).
setParameter("currency", String.valueOf(currency)).
setResultTransformer(
Transformers.aliasToBean(BookingSummary.class)
).list();
I had a few summaries, that needed left outer joins, so no way to map it back into entities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With