I am trying to map the result of a native query with joins to Projection (Interface) which is not an entity. I have to map Postgres array codes| text[]|
to String[] getCodes(); in projection interface. With Entity, it can easily be mapped defining types below and then annotating the properties
@TypeDef(
name = "string-array",
typeClass = StringArrayType.class
)
})
But the same seems not working with projections. Is there any way to do the same with projection without casting the array to text in the query itself?
What does your native query do, maybe you can use Blaze-Persistence Entity Views on top of JPA/Hibernate instead to stay in the realm of the JPA model?
Blaze-Persistence is a query builder on top of JPA which supports many of the advanced DBMS features on top of the JPA model. I created Entity Views on top of it to allow easy mapping between JPA models and custom interface defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure the way you like and map attributes(getters) via JPQL expressions to the entity model. Since the attribute name is used as default mapping, you mostly don't need explicit mappings as 80% of the use cases is to have DTOs that are a subset of the entity model.
A DTO mapping for your model could look as simple as the following
@EntityView(SomeEntity.class)
interface SomeEntityProjection {
Integer getId();
String[] getCodes();
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
SomeEntityProjection dto = entityViewManager.find(entityManager, SomeEntityProjection.class, id);
But the Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
It will only fetch the mappings that you tell it to fetch.