如何通过构造函数和JPQL生成DTO?

栏目: Java · 发布时间: 7年前

内容简介:获取超出需要的数据更容易导致性能损失。使用DTO可以让我们只提取所需的数据。在这个应用程序中,我们依赖于Constructor Expression和JPQLL生成DTO。点击#DTO标签可获得更多生成DTO的方式。同样,在DDD编程中,从DDD聚合中获取DDD值对象有多种方式,如果我们不使用DTO方式,直接返回完整实体聚合,容易导致性能损失,使用DTO可以让我们只提取所需的数据。1. 编写一个带有构造参数的DTO,其实这是一个DDD值对象:

获取超出需要的数据更容易导致性能损失。使用DTO可以让我们只提取所需的数据。在这个应用程序中,我们依赖于Constructor Expression和JPQLL生成DTO。点击#DTO标签可获得更多生成DTO的方式。

同样,在DDD编程中,从DDD聚合中获取DDD值对象有多种方式,如果我们不使用DTO方式,直接返回完整实体聚合,容易导致性能损失,使用DTO可以让我们只提取所需的数据。

1. 编写一个带有构造参数的DTO,其实这是一个DDD值对象:

<b>public</b> <b>class</b> CarDto implements Serializable {

    <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L;

    <b>private</b> <b>final</b> String name;
    <b>private</b> <b>final</b> String color;

    <b>public</b> CarDto(String name, String color) {
        <b>this</b>.name = name;
        <b>this</b>.color = color;
    }

2. 编写自己的DAO,使用JPQL“select new com.jpa.CarDto(c.name, c.color) from Car c”创建带参数的DTO。

@Repository
@Transactional
<b>public</b> <b>class</b> Dao<T, ID <b>extends</b> Serializable> implements GenericDao<T, ID> {

    @PersistenceContext
    <b>private</b> EntityManager entityManager;

    @Override
    <b>public</b> <S <b>extends</b> T> S persist(S entity) {
        
        Objects.requireNonNull(entity, <font>"Cannot persist a null entity"</font><font>);
        
        entityManager.persist(entity);

        <b>return</b> entity;
    }

    @Transactional(readOnly=<b>true</b>)
    <b>public</b> List<CarDto> fetchCars() {
        Query query = entityManager
                .createQuery(</font><font>"select new com.jpa.CarDto(c.name, c.color) from Car c"</font><font>,
                        CarDto.<b>class</b>);                
        List<CarDto> result = query.getResultList();

        <b>return</b> result;
    }
</font>

Service调用:

@Service
<b>public</b> <b>class</b> CarService {

    <b>private</b> <b>final</b> Dao dao;

    <b>public</b> CarService(Dao dao) {
        <b>this</b>.dao = dao;
    }

    <b>public</b> List<CarDto> fetchCars() {
        <b>return</b> dao.fetchCars();
    }
}

源码下载


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Complexity and Approximation

Complexity and Approximation

G. Ausiello、P. Crescenzi、V. Kann、Marchetti-sp、Giorgio Gambosi、Alberto M. Spaccamela / Springer / 2003-02 / USD 74.95

This book is an up-to-date documentation of the state of the art in combinatorial optimization, presenting approximate solutions of virtually all relevant classes of NP-hard optimization problems. The......一起来看看 《Complexity and Approximation》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码