如何透過javax.persistence.Tuple和原生SQL生成DTO?

banq發表於2019-02-12

從實體中獲取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")));
        };
    }
}


原始碼下載

相關文章