DTO将使用与实体对象相同的字符串池。如果您的实体中有复杂的对象,您可以在DTO和实体之间进行浅拷贝。
使用DTO将保护服务层方法不暴露实体设计。使用DTO不应导致显著的性能问题。
我采用编写XSD
模式定义DTO
对象的方法,然后使用插件生成实际的POJOs
。在我的entities
中,我添加了toEntityType
和fromEntityType
翻译方法。这将DTO翻译直接耦合到实体和控制服务中。我不需要编写POJOs,而XSD作为文档。例如,一个实体。
public class Product {
private Long id;
private String name;
/**
* Fill out properties from PurchaseOrderType. Copies all dependencies.
* @param productType {@link ProductType}
* @return Product
*/
public Product fromProductType(ProductType productType) {
this.id = productType.getId();
this.name = productType.getName();
return this;
}
/**
* Create and return ProductType representation.
* @return {@link ProductType}
*/
public ProductType asProductType() {
ProductType productType = new ProductType();
productType.setId(id);
productType.setName(name);
return productType;
}
... getters, setters,
}
<!-- product -->
<xsd:element name="productType">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:long" minOccurs="0"/>
<xsd:element name="name" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.13.2</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
以及一个服务
/**
* Rest endpoint for a ProductType
* rest/productservice/getproduct/{id}
* @param id @{link Long}
* @return {@link ProductType}
*/
@GET
@Path("getproduct/{id}")
@Produces({MediaType.APPLICATION_JSON})
public ProductType getProduct(@PathParam("id") Long id) throws Exception {
// retrieve product information based on the id supplied in the formal argument
Product getProduct = productDao.getProduct(id);
if ( getProduct == null )
throw new IllegalArgumentException("Product not found for id: " + id);
ProductType productType = getProduct.asProductType();
return productType;
}
实际上,您甚至可以通过使用DTO方法来提高性能,因为您可以查询更少的数据,假设DTO不是您实体模型的1:1副本。 我写了一篇文章,介绍了使用实体模型时遇到的问题以及如何使用Blaze-Persistence Entity Views有效地实现DTO方法。也许您想尝试一下,看看它如何改善您的设计和性能!