Thursday, 15 July 2010

JPA EntityManager TypedQuery -- Return a Different Class (ViewModel/DTO) than entity model? -



JPA EntityManager TypedQuery -- Return a Different Class (ViewModel/DTO) than entity model? -

coming entity framework background can cast orm results class contains subset of total back-end model's data.

i have jax-rs rest service returning like

myentity result = em.createquery(select e myentity e ... blah blah blah).

i know can this:

object result = em.createquery(select e.title, e.version, e.date myentity e... blah blah blah).

but can either a: cast result separate class or b name fields in createquery such named when returning json?

for illustration in .net land like....

(select new {title = e.title, version = e.version})

and cast type. tried using typedquery , casting "type x incompatible homecoming type y" type error.

my goal homecoming specific subset (view model/ dto)of info consumption in specific scenario.

e.g model huge , don't want homecoming big amount of info every time.

yes, creating non-entity types possible, using jpa constructor expressions i.e. new keyword:

list<dto> dtos = em.createquery("select new com.example.dto( o.title, o.version) entity o").getresultlist();

the dto must have constructor relevant fields.

there no need casting.

jpa entitymanager

No comments:

Post a Comment