JPA has met today with the need to query the data, and convert the result to the DTO scene, we found the two methods, here the record about
Wherein the entity class:
@Data @Entity @Table(name = "CLASSIFY_PERSON") public class ClassifyPerson { @Id private String id; @Column private String classifyId; @Column private String accountNo; @Column private String name; }
A local SQL + Interface
1. The need to define interfaces results:
public interface Person{ String getAccountNo(); String getName(); }
2. Define Query
@Query(value = "select account_no as accountNo, name from CLASSIFY_PERSON where classify_id = ?1", nativeQuery = true) List<Person> findByClassifyId(String classifyId);
Two, HQL + DTO way
1. DTO class definitions (model the package):
@Data @AllArgsConstructor public class PersonDTO { private String accountNo; private String name; }
2. Define Query
@Query(value = "select new model.PersonDTO(accountNo, name) from ClassifyPerson where classifyId = ?1")
List<PersonDTO> findByClassifyId(String classifyId);
Above two methods can achieve proven data conversion