通過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 = <font>"car"</font><font>) <b>public</b> <b>class</b> Car implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) <b>private</b> Long id; <b>private</b> String name; <b>private</b> String engine; <b>private</b> String color; </font>
編制自己的DAO:
@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<Tuple> fetchCars() { List<Tuple> result = entityManager .createNativeQuery( </font><font>"select name, color from car"</font><font>, Tuple.<b>class</b> ).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<Tuple> fetchCars() { <b>return</b> dao.fetchCars(); } }
最終Spring Boot中呼叫:
@SpringBootApplication <b>public</b> <b>class</b> TupleAndSqlApplication { <b>private</b> <b>static</b> <b>final</b> Logger logger = Logger.getLogger(TupleAndSqlApplication.<b>class</b>.getName()); @Autowired <b>private</b> CarService carService; <b>public</b> <b>static</b> <b>void</b> main(String[] args) { SpringApplication.run(TupleAndSqlApplication.<b>class</b>, args); } @Bean <b>public</b> ApplicationRunner init() { <b>return</b> args -> { carService.populateCars(); List<Tuple> cars = carService.fetchCars(); cars.forEach((e) -> logger.info(() -> <font>"Car: "</font><font> + e.get(</font><font>"name"</font><font>) + </font><font>","</font><font> + e.get(</font><font>"color"</font><font>))); }; } } </font>