Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 36 design patterns After youve defined your DTO you can use it as a projection in your JPQL Criteria and native queries JPA supports constructor expressions in JPQL and CriteriaQuery queries and you can use @ SqlResultSetMapping to map the result of your native queries for each retrieved record In all cases your persistence provider selects the specified database columns and calls the constructor referenced in the constructor expression for each record of the result set The following code snippet shows an example of a JPQL query using a constructor expression It consists of the keyword new followed by the fully referenced class name of the DTO and one or more entity attributes that define the parameters TypedQuery EmployeeWithDepartment q em createQuery SELECT new org thoughts on java model EmployeeWithDepartment e firstName e lastName e department name FROM Employee e WHERE e id id EmployeeWithDepartment class q setParameter id 1L q getSingleResult As you have seen you can easily map each record of your query result to a DTO But when should you use DTOs Reasons to use DTOs If you implement and deploy your presentation and business layers independently of each other for example a Java microservice with a REST API and a JavaScript front end youll want to create a stable API that doesnt leak any internal information or design decisions This enables you to adapt your business layer to new requirements or to improve the existing implementation without changing the API It also enables you to exclude some entity attributes from your API for example internal attributes that shouldnt be visible to any user or huge lists of associated entities Especially in REST APIs its better to provide a link to another REST endpoint that provides you the requested resources instead of including them in the returned JSON document
You must have JavaScript enabled to view digital editions.