Is it possible to create a spring JPA DTO projection from a sub class of a full JPA entity?

69 Views Asked by At

Given a basic JPA entity:

@Entity
class Person {
    String name;
    Integer age;
    //getters and setters
}

I need to create a spring JPA DTO projection like the follwing:

class PersonProjection {
    String name;
    Integer age;
    String projectionProperty;
    //getters and setters
}

The projectionProperty is not something that could be handled via @Formula or standard jpa relationship, hence the use of a Projection.

Given that the projection has much in common with the entity, is it possible to use inheritance e.g.:

class PersonProjection extends Person {
   String projectionProperty;
   //getters and setters
}

Currently when trying to do this and calling the spring JPA repo method, I get an org.hibernate.MappingException: Unknown entity: PersonProjection exception. I assume because spring doesn't realize that I am attempting to use a projection and instead wants to retrieve an entity, due to @Entity being on the parent class.

Is there a way I can indicate that although PersonProjection extends an entity, it is not an entity for the purposes of my specific repository method? Perhaps by excluding the subclass from JPA, or annotating the spring repo method?

Edit: Using projection interfaces (as I understand them) isn't a complete solution for my use case because downstream code needs the results to be Person entity instances, so the query results would have to be re-mapped manually into PersonProjection instances - which is what Im trying to avoid to begin with.

0

There are 0 best solutions below