如何通过javax.persistence.Tuple和原生SQL生成DTO?


从实体中获取DTO数据,也就是从DDD聚合中获取DDD值对象有多种方式,如果我们不使用DTO方式,直接返回完整实体聚合,容易导致性能损失,使用DTO可以让我们只提取所需的数据。在这个应用程序中,我们展示如何依赖于javax.persistence.Tuple原生SQL生成DTO。点击DTO标签可获得更多生成DTO的方式

主要点:
编制自己的Dao调用EntityManager.createNativeQuery(),返回java.persistence.Tuple类型:

假设Car实体:


@Entity
@Table(name = "car")
public class Car implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String engine;
    private String color;

编制自己的DAO:


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

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public <S extends T> S persist(S entity) {

        Objects.requireNonNull(entity, "Cannot persist a null entity");

        entityManager.persist(entity);

        return entity;
    }

    @Transactional(readOnly = true)
    public List<Tuple> fetchCars() {
        List<Tuple> result = entityManager
                .createNativeQuery(
                       
"select name, color from car", Tuple.class
                ).getResultList();

        return result;
    }

Service调用:


@Service
public class CarService {

    private final Dao dao;

    public CarService(Dao dao) {
        this.dao = dao;
    }

    public List<Tuple> fetchCars() {
        return dao.fetchCars();
    }
}


最终Spring Boot中调用:


@SpringBootApplication
public class TupleAndSqlApplication {
    
    private static final Logger logger
            = Logger.getLogger(TupleAndSqlApplication.class.getName());
    
    @Autowired
    private CarService carService;
    
    public static void main(String args) {
        SpringApplication.run(TupleAndSqlApplication.class, args);
    }
    
    @Bean
    public ApplicationRunner init() {
        return args -> {
            
            carService.populateCars();
            List<Tuple> cars = carService.fetchCars();
            
            cars.forEach((e) -> logger.info(() -> "Car: " + e.get("name") + "," + e.get("color")));
        };
    }
}

源码下载